prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
python dictionary from an object fields do you know if there is built in function to build dictionary from an arbitrary object would like to do something like this class foo bar hello baz world foo props bar hello baz world note it should not include methods only fields thanks
|
note that best practice in current versions of python is to use new style classes class foo object also there is difference between an object and class to build dictionary from an arbitrary object it is sufficient to use dict usually you will declare your methods at class level and your attributes at instance level so dict should be fine for example class object def init self self self def do nothing self pass dict alternatively depending on what you want to do it might be nice to inherit from dict then your class is already dictionary and if you want you can override getattr and or setattr to call through and set the dict for example class foo dict def init self pass def getattr self attr return self attr etc
|
QA
|
how would you design very pythonic ui framework have been playing with the ruby library shoes basically you can write gui application in the following way shoes app do para not clicked button the label do alert you clicked the button when clicked make an alert replace clicked and replace the label text end end this made me think how would design similarly nice to use gui framework in python one that does not have the usual tyings of basically being wrappers to library in the case of gtk tk wx qt etc etc shoes takes things from web devlopment like style colour notation css layout techniques like margin and from ruby extensively using blocks in sensible ways python lack of rubyish blocks makes metaphorically direct port impossible def shoeless shoes app self para not clicked def on click func self alert you clicked the button self replace clicked button the label click self on click func no where near as clean and would not be nearly as flexible and am not even sure if it would be implementable using decorators seems like an interesting way to map blocks of code to specific action class basecontrol def init self self func none def clicked self func self func func def call self if self func is not none self func class button basecontrol pass class label basecontrol pass the actual applications code that the end user would write class myapp ok button la label ok clicked def clickeryhappened print ok clicked if name main myapp ok trigger the clicked action basically the decorator function stores the function then when the action occurred say click the appropriate function would be executed the scope of various stuff say the la label in the above example could be rather complicated but it seems doable in fairly neat manner
|
with some metaclass magic to keep the ordering have the following working am not sure how pythonic it is but it is good fun for creating simple things class wndw title hello world class txt txt either new class text insert name here lbl lbl text hello or an instance class greet bbt text greet def click self on click method self frame lbl text hello self frame txt text app
|
QA
|
any good ajax framework for google app engine apps am trying to implement ajax in my google app engine application and so am looking for good ajax framework that will help me anyone has any idea am thinking about google web toolkit how good it is in terms of creating ajax for google app engine
|
if you want to be able to invoke method calls from javascript to python json rpc works well with google app engine see google article using ajax to enable client rpc requests for details
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
no how would python parse your script if there was way to disable this
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
no indentation as grammar is an integral part of the python language for better and worse
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
do not believe so as python is whitespace delimited language perhaps text editor or ide with auto indentation would be of help what are you currently using
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
no there is not indentation is syntax for python you can use tabnanny py to check your code use syntax aware editor that highlights such mistakes vi does that emacs bet it does and then most ides do too far fetched write preprocessor of your own to convert braces or whatever block delimiters you love into indentation
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
all of the whitespace issues had when was starting python were the result mixing tabs and spaces once configured everything to just use one or the other stopped having problems in my case configured ultraedit vim to use spaces in place of tabs
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
you should disable tab characters in your editor when you are working with python always actually imho but especially when you are working with python look for an option like use spaces for tabs any decent editor should have one
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
not really there are few ways to modify whitespace rules for given line of code but you will still need indent levels to determine scope you can terminate statements with and then begin new statement on the same line which people often do when golfing if you want to break up single line into multiple lines you can finish line with the character which means the current line effectively continues from the first non whitespace character of the next line this visually appears violate the usual whitespace rules but is legal my advice do not use tabs if you are having tab space confusion use spaces and choose either or spaces as your indent level good editor will make it so you do not have to worry about this python mode for emacs for example you can just use the tab key and it will keep you honest
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
it is possible to write pre processor which takes randomly indented code with pseudo python keywords like endif and endwhile and properly indents things had to do this when using python as an asp like language because the whole notion of indentation gets bit fuzzy in such an environment of course even with such thing you really ought to indent sanely at which point the conveter becomes superfluous
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
agree with justin and others pick good editor and use spaces rather than tabs for indentation and the whitespace thing becomes non issue only recently started using python and while thought the whitespace issue would be real annoyance it turns out to not be the case for the record am using emacs though am sure there are other editors out there that do an equally fine job if you are really dead set against it you can always pass your scripts through pre processor but that is bad idea on many levels if you are going to learn language embrace the features of that language rather than try to work around them otherwise what is the point of learning new language
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
getting your indentation to work correctly is going to be important in any language you use even though it will not affect the execution of the program in most other languages incorrect indentation can be very confusing for anyone trying to read your program so you need to invest the time in figuring out how to configure your editor to align things correctly python is pretty liberal in how it let us you indent you can pick between tabs and spaces but you really should use spaces and can pick how many spaces the only thing it requires is that you are consistent which ultimately is important no matter what language you use
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
am currently using notepad is there maybe an ide that would take care of the tabs and indenting liked pydev extensions of eclipse for that
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
tabs and spaces confusion can be fixed by setting your editor to use spaces instead of tabs to make whitespace completely intuitive you can use stronger code editor or an ide though you do not need full blown ide if all you need is proper automatic code indenting list of editors can be found in the python wiki though that one is bit too exhausting http wiki python org moin pythoneditors there is already question in here which tries to slim that down bit http stackoverflow com questions poll which python ideeditor is the best maybe you should add more specific question on that which python editor or ide do you prefer on windows and why
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
was bit reluctant to learn python because of tabbing however almost did not notice it when used vim
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
it is fine to return multiple values using tuple for simple functions such as divmod if it makes the code readable it is pythonic if the return value starts to become confusing check whether the function is doing too much and split it if it is if big tuple is being used like an object make it an object also consider using named tuples which will be part of the standard library in python
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
it is definitely pythonic the fact that you can return multiple values from function the boilerplate you would have in language like where you need to define struct for every combination of types you return somewhere however if you reach the point where you are returning something crazy like values from single function you should seriously consider bundling them in class because at that point it gets unwieldy
|
QA
|
which is the most useful mercurial hook for programming in loosely connected team recently discovered the notify extension in mercurial which allows me quickly send out emails whenever push changes but am pretty sure am still missing out on lot of functionality which could make my life lot easier notify extension http www selenic com mercurial wiki index cgi notifyextension which mercurial hook or combination of interoperating hooks is the most useful for working in loosely connected team please add links to non standard parts you use and or add the hook or description how to set it up so others can easily use it
|
take look at the hgweb stuff you can set up rss feeds and see all the revisions et cetera
|
QA
|
python dictionary from an object fields do you know if there is built in function to build dictionary from an arbitrary object would like to do something like this class foo bar hello baz world foo props bar hello baz world note it should not include methods only fields thanks
|
to build dictionary from an arbitrary object it is sufficient to use dict this misses attributes that the object inherits from its class for example class object hasattr is true but does not appear in dict
|
QA
|
which is the most useful mercurial hook for programming in loosely connected team recently discovered the notify extension in mercurial which allows me quickly send out emails whenever push changes but am pretty sure am still missing out on lot of functionality which could make my life lot easier notify extension http www selenic com mercurial wiki index cgi notifyextension which mercurial hook or combination of interoperating hooks is the most useful for working in loosely connected team please add links to non standard parts you use and or add the hook or description how to set it up so others can easily use it
|
really enjoy what did with my custom hook have it post message to my campfire account campfire is group based app it worked out really well because had my clients in there and it could show him my progress
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
when writing package called foo will put unit tests into separate package foo test modules and subpackages will then have the same name as the sut package module tests for module foo are found in foo test the init py files of each testing package then contain an alltests suite that includes all test suites of the package setuptools provides convenient way to specify the main testing package so that after python setup py develop you can just use python setup py test or python setup py test foo test sometestsuite to the just specific suite
|
QA
|
how create threads under python for delphi am hosting python script with python for delphi components inside my delphi application would like to create background tasks which keep running by script is it possible to create threads which keep running even if the script execution ends but not the host process which keeps going on have noticed that the program gets stuck if the executing script ends and there is thread running however if will wait until the thread is finished everything goes fine am trying to use threading standard module for threads
|
threads by definition are part of the same process if you want them to keep running they need to be forked off into new process see os fork and friends you will probably want the new process to end via exit or the like immediately after spawning the script
|
QA
|
how create threads under python for delphi am hosting python script with python for delphi components inside my delphi application would like to create background tasks which keep running by script is it possible to create threads which keep running even if the script execution ends but not the host process which keeps going on have noticed that the program gets stuck if the executing script ends and there is thread running however if will wait until the thread is finished everything goes fine am trying to use threading standard module for threads
|
if process dies all it is threads die with it so solution might be separate process see if creating xmlrpc server might help you that is simple solution for interprocess communication
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
returning tuple is cool also note the new namedtuple which was added in python which may make this more palatable for you http docs python org dev library collections html collections namedtuple
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
find it hard to understand when people flag this as problem with python took to it immediately and actually find it is one of my favourite features of the language in other languages have two jobs fix the braces so the computer can parse my code fix the indentation so can parse my code so in python have half as much to worry about nb the only time ever have problem with indendation is when python code is in blog and forum that messes with the white space but this is happening less and less as the apps get smarter
|
QA
|
passing on named variable arguments in python say have the following methods def methoda arg kwargs pass def methodb arg args kwargs pass in methoda wish to call methodb passing on the kwargs however it seems that if define methoda as follows the second argument will be passed on as positional rather than named variable arguments def methoda arg kwargs methodb argvalue kwargs how do make sure that the kwargs in methoda gets passed as kwargs to methodb
|
as an aside when using functions instead of methods you could also use functools partial import functools def foo arg kwargs bar functools partial foo argvalue the last line will define function bar that when called will call foo with the first argument set to argvalue and all other functions just passed on bar myarg value will call foo argvalue myarg value unfortunately that will not work with methods
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
if you are looking for recommendation for python ide after extensive research have been most happy with wing software wingide http www wingware com products there is free trial version so you have nothing to lose it supports all the major oses and is only about for the full version also like scite lot which is totally free free free http scintilla sourceforge net scitedownload html
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
yes returning multiple values tuple is definitely pythonic as others have pointed out there are plenty of examples in the python standard library as well as in well respected python projects two additional comments returning multiple values is sometimes very very useful take for example method that optionally handles an event returning some value in doing so and also returns success or failure this might arise in chain of responsibility pattern in other cases you want to return multiple closely linked pieces of data as in the example given in this setting returning multiple values is akin to returning single instance of an anonymous class with several member variables python handling of method arguments necessitates the ability to directly return multiple values in for example method arguments can be passed by reference so you can assign output values to them in addition to the formal return value in python arguments are passed by reference but in the sense of java not you cannot assign new values to method arguments and have it reflected outside method scope for example void test int arg arg int foo test foo foo is now compare with python def test arg arg foo test foo foo is still
|
QA
|
can someone explain all in python have been using python more and more and keep seeing the variable all set in different init py files can someone explain what this does
|
linked to but not explicitly mentioned here is exactly when all is used it is list of strings defining what symbols in module will be exported when from module import is used on the module for example the following code in foo py explicitly exports the symbols bar and baz all bar baz waz bar def baz return baz these symbols can then be imported like so from foo import print bar print baz the following will trigger an exception as waz is not exported by the module print waz if the all above is commented out this code will then execute to completion as the default behaviour of import is to import all symbols that do not begin with an underscore from the given namespace reference https docs python org tutorial modules html importing from package note all affects the from module import behavior only members that are not mentioned in all are still accessible from outside the module and can be imported with from module import member
|
QA
|
classes in python in python is there any way to make class then make second version of that class with identical dat but which can be changed then reverted to be the same as the data in the original class so would make class with the numbers to as the data in it then make second class with the same names for sections or very similar mess around with the numbers in the second class then with one function then reset them to be the same as in the first class the only alternative have found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable
|
class is template it allows you to create blueprint you can then have multiple instances of class each with different numbers like so class dog object def init self height width lenght self height height self width width self length length def revert self self height self width self length dog dog dog dog dog revert
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
many python ides and generally capable text source editors can handle the whitespace for you however it is best to just let go and enjoy the whitespace rules of python with some practice they will not get into your way at all and you will find they have many merits the most important of which are because of the forced whitespace python code is simpler to understand you will find that as you read code written by others it is easier to grok than code in say perl or php whitespace saves you quite few keystrokes of control characters like and which litter code written in like languages less and means among other things less rsi and wrist pain this is not matter to take lightly
|
QA
|
classes in python in python is there any way to make class then make second version of that class with identical dat but which can be changed then reverted to be the same as the data in the original class so would make class with the numbers to as the data in it then make second class with the same names for sections or very similar mess around with the numbers in the second class then with one function then reset them to be the same as in the first class the only alternative have found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable
|
classes do not have values objects do is what you want basically class that can reset an instance object to set of default values how about just providing reset method that resets the properties of your object to whatever is the default think you should simplify your question or tell us what you really want to do it is not at all clear
|
QA
|
classes in python in python is there any way to make class then make second version of that class with identical dat but which can be changed then reverted to be the same as the data in the original class so would make class with the numbers to as the data in it then make second class with the same names for sections or very similar mess around with the numbers in the second class then with one function then reset them to be the same as in the first class the only alternative have found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable
|
think you are confused you should re check the meaning of class and instance think you are trying to first declare instance of certain class and then declare instance of other class use the data from the first one and then find way to convert the data in the second instance and use it on the first instance recommend that you use operator overloading to assign the data
|
QA
|
classes in python in python is there any way to make class then make second version of that class with identical dat but which can be changed then reverted to be the same as the data in the original class so would make class with the numbers to as the data in it then make second class with the same names for sections or very similar mess around with the numbers in the second class then with one function then reset them to be the same as in the first class the only alternative have found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable
|
class abc self numbers class def abc def init self self new numbers super abc self numbers def setnums self numbers self new numbers numbers def getnums self return self new numbers def reset self init
|
QA
|
how do you retrieve items from dictionary in the order that they are inserted is it possible to retrieve items from python dictionary in the order that they were inserted
|
if you do not need the dict functionality and only need to return tuples in the order you have inserted them would not queue work better
|
QA
|
when to create new app with startapp in django have googled around for this but still have trouble relating to what django defines as apps should create new app for each piece of functionality in site even though it uses models from the main project do you guys have good rule of thumb of when to split off new app and when to keep functionality together with the main project or other apps
|
tend to create new applications for each logically separate set of models user profiles forum posts blog posts
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
pybraces it is unsupported
|
QA
|
classes in python in python is there any way to make class then make second version of that class with identical dat but which can be changed then reverted to be the same as the data in the original class so would make class with the numbers to as the data in it then make second class with the same names for sections or very similar mess around with the numbers in the second class then with one function then reset them to be the same as in the first class the only alternative have found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable
|
just fyi here is an alternate implementation probably violates about million pythonic rules but publish it per information observation class resettable object base dict def reset self self dict self class base dict def init self self dict self class base dict copy class someclass resettable base dict number one number two number three number four number five def init self resettable init self someclass number one print number one reset print number one
|
QA
|
when to create new app with startapp in django have googled around for this but still have trouble relating to what django defines as apps should create new app for each piece of functionality in site even though it uses models from the main project do you guys have good rule of thumb of when to split off new app and when to keep functionality together with the main project or other apps
|
prefer to think of django applications as reusable modules or components than as applications this helps me encapsulate and decouple certain features from one another improving re usability should decide to share particular app with the community at large and maintainability my general approach is to bucket up specific features or feature sets into apps as though were going to release them publicly the hard part here is figuring out how big each bucket is good trick use is to imagine how my apps would be used if they were released publicly this often encourages me to shrink the buckets and more clearly define its purpose
|
QA
|
best python supported server client protocol am looking for good server client protocol supported in python for making data requests file transfers between one server and many clients security is also an issue so secure login would be plus have been looking into xml rpc but it looks to be pretty old and possibly unused these days protocol
|
pyro python remote objects is fairly clever if all your server clients are going to be in python use xmpp alot though since am communicating with hosts that are not always python xmpp lends itself to being extended fairly easily too there is an excellent xmpp library for python called pyxmpp which is reasonably up to date and has no dependancy on twisted
|
QA
|
how can make time delay in python would like to know how to put time delay in python script
|
you can use the sleep function in the time module it can take float argument for sub second resolution from time import sleep sleep time in seconds
|
QA
|
best python supported server client protocol am looking for good server client protocol supported in python for making data requests file transfers between one server and many clients security is also an issue so secure login would be plus have been looking into xml rpc but it looks to be pretty old and possibly unused these days protocol
|
would use http and start with understanding what the python library offers then would move onto the more industrial strength twisted library
|
QA
|
best python supported server client protocol am looking for good server client protocol supported in python for making data requests file transfers between one server and many clients security is also an issue so secure login would be plus have been looking into xml rpc but it looks to be pretty old and possibly unused these days protocol
|
http seems to suit your requirements and is very well supported in python twisted is good for serious asynchronous network programming in python but it has steep learning curve so it might be worth using something simpler unless you know your system will need to handle lot of concurrency to start would suggest using urllib for the client and wsgi service behind apache for the server apache can be set up to deal with https fairly simply
|
QA
|
when to create new app with startapp in django have googled around for this but still have trouble relating to what django defines as apps should create new app for each piece of functionality in site even though it uses models from the main project do you guys have good rule of thumb of when to split off new app and when to keep functionality together with the main project or other apps
|
james bennett has wonderful set of slides on how to organize reusable apps in django
|
QA
|
sending mail from python using smtp am using the following method to send mail from python using smtp is it the right method to use or are there gotchas am missing from smtplib import smtp import datetime debuglevel smtp smtp smtp set debuglevel debuglevel smtp connect your mail server smtp login username domain password from addr john doe john doe net to addr foo bar com subj hello date datetime datetime now strftime message text hello nthis is mail from your server nbye message from nto nsubject ndate from addr to addr subj date message text smtp sendmail from addr to addr message smtp quit
|
the main gotcha see is that you are not handling any errors login and sendmail both have documented exceptions that they can throw and it seems like connect must have some way to indicate that it was unable to connect probably an exception thrown by the underlying socket code
|
QA
|
sending mail from python using smtp am using the following method to send mail from python using smtp is it the right method to use or are there gotchas am missing from smtplib import smtp import datetime debuglevel smtp smtp smtp set debuglevel debuglevel smtp connect your mail server smtp login username domain password from addr john doe john doe net to addr foo bar com subj hello date datetime datetime now strftime message text hello nthis is mail from your server nbye message from nto nsubject ndate from addr to addr subj date message text smtp sendmail from addr to addr message smtp quit
|
you should make sure you format the date in the correct format rfc
|
QA
|
sending mail from python using smtp am using the following method to send mail from python using smtp is it the right method to use or are there gotchas am missing from smtplib import smtp import datetime debuglevel smtp smtp smtp set debuglevel debuglevel smtp connect your mail server smtp login username domain password from addr john doe john doe net to addr foo bar com subj hello date datetime datetime now strftime message text hello nthis is mail from your server nbye message from nto nsubject ndate from addr to addr subj date message text smtp sendmail from addr to addr message smtp quit
|
make sure you do not have any firewalls blocking smtp the first time tried to send an email it was blocked both by windows firewall and mcafee took forever to find them both
|
QA
|
best python supported server client protocol am looking for good server client protocol supported in python for making data requests file transfers between one server and many clients security is also an issue so secure login would be plus have been looking into xml rpc but it looks to be pretty old and possibly unused these days protocol
|
xmlrpc is very simple to get started with and at my previous job we used it extensively for intra node communication in distributed system as long as you keep track of the fact that the none value cannot be easily transferred it is dead easy to work with and included in python standard library run it over https and add username password parameter to all calls and you will have simple security in place not sure about how easy it is to verify server certificate in python though however if you are transferring large amounts of data the coding into xml might become bottleneck so using rest inspired architecture over https may be as good as xmlrpclib
|
QA
|
sending mail from python using smtp am using the following method to send mail from python using smtp is it the right method to use or are there gotchas am missing from smtplib import smtp import datetime debuglevel smtp smtp smtp set debuglevel debuglevel smtp connect your mail server smtp login username domain password from addr john doe john doe net to addr foo bar com subj hello date datetime datetime now strftime message text hello nthis is mail from your server nbye message from nto nsubject ndate from addr to addr subj date message text smtp sendmail from addr to addr message smtp quit
|
the script use is quite similar post it here as an example of how to use the email modules to generate mime messages so this script can be easily modified to attach pictures etc rely on my isp to add the date time header my isp requires me to use secure smtp connection to send mail rely on the ssmtplib module downloadable at http www cs columbia edu db ssmtplib py as in your script the username and password given dummy values below used to authenticate on the smtp server are in plain text in the source this is security weakness but the best alternative depends on how careful you need want to be about protecting these usr local bin python smtpserver smtp att yahoo com sender me my email domain net destination recipient her email domain com username user name for internet service provider password password internet service provider typical values for text subtype are plain html xml text subtype plain content test message subject sent from python import sys import os import re from smtplib import smtp ssl as smtp this invokes the secure smtp protocol port uses ssl from smtplib import smtp use this for standard smtp protocol port no encryption old version from email mimetext import mimetext from email mime text import mimetext try message mimetext content text subtype message subject subject message from sender some smtp servers will do this automatically not all conn smtp smtpserver conn set debuglevel false conn login username password try conn sendmail sender destination message as string finally conn quit except exception exc sys exit mail failed str exc give error message
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
in python indentation is semantic element as well as providing visual grouping for readability both space and tab can indicate indentation this is unfortunate because the interpretation of tab varies among editors and ides and is often configurable and often configured otoh some editors are not configurable but apply their own rules for indentation different sequences of spaces and tabs may be visually indistinguishable cut and pastes can alter whitespace so unless you know that given piece of code will only be modified by yourself with single tool and an unvarying config you must avoid tabs for indentation configure your ide and make sure that you are warned if they are introduced search for tabs in leading whitespace and you can still expect to be bitten now and then as long as arbitrary semantics are applied to control characters
|
QA
|
python regular expression for html parsing beautifulsoup want to grab the value of hidden input field in html input type hidden name fooid value want to write regular expression in python that will return the value of fooid given that know the line in the html follows the format input type hidden name fooid value id is here can someone provide an example in python to parse the html for the value
|
agree with vinko beautifulsoup is the way to go however suggest using fooid value to get the attribute rather than relying on value being the third attribute from beautifulsoup import beautifulsoup or retrieve it from the web etc html data open yourwebsite page html read create the soup object from the html data soup beautifulsoup html data fooid soup find input name fooid type hidden find the proper tag value fooid value the value attribute
|
QA
|
how to setup vim autoindentation properly for editing python files py have troubles setting vim xxx for editing python files indenting seems to be broken optimal spaces have followed some tutorials found via google still no effect please help
|
use this on my macbook configure expanding of tabs for various file types au bufread bufnewfile py set expandtab au bufread bufnewfile set noexpandtab au bufread bufnewfile set noexpandtab au bufread bufnewfile makefile set noexpandtab configure editor with tabs and nice stuff set expandtab enter spaces when tab is pressed set textwidth break lines when line length increases set tabstop use spaces to represent tab set softtabstop set shiftwidth number of spaces to use for auto indent set autoindent copy indent from current line when starting new line make backspaces more powerfull set backspace indent eol start set ruler show line and column number syntax on syntax highlighting set showcmd show partial command in status line edited to only show stuff related to indent tabs
|
QA
|
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
|
print str output
|
QA
|
how do you retrieve items from dictionary in the order that they are inserted is it possible to retrieve items from python dictionary in the order that they were inserted
|
have used stabledict before with good success http pypi python org pypi stabledict
|
QA
|
caching compiled regex objects in python each time python file is imported that contains large quantity of static regular expressions cpu cycles are spent compiling the strings into their representative state machines in memory re compile re compile question is it possible to store these regular expressions in cache on disk in pre compiled manner to avoid having to execute the regex compilations on each import pickling the object simply does the following causing compilation to happen anyway import pickle import re re compile pickle dumps cre compile np np ni ntp nrp and re objects are unmarshallable import marshal import re re compile marshal dumps traceback most recent call last file stdin line in module valueerror unmarshallable object
|
note that each module initializes itself only once during the life of an app no matter how many times you import it so if you compile your expressions at the module global scope ie not in function you should be fine
|
QA
|
caching compiled regex objects in python each time python file is imported that contains large quantity of static regular expressions cpu cycles are spent compiling the strings into their representative state machines in memory re compile re compile question is it possible to store these regular expressions in cache on disk in pre compiled manner to avoid having to execute the regex compilations on each import pickling the object simply does the following causing compilation to happen anyway import pickle import re re compile pickle dumps cre compile np np ni ntp nrp and re objects are unmarshallable import marshal import re re compile marshal dumps traceback most recent call last file stdin line in module valueerror unmarshallable object
|
is it possible to store these regular expressions in cache on disk in pre compiled manner to avoid having to execute the regex compilations on each import not easily you would have to write custom serializer that hooks into the sre implementation of the python regex engine any performance benefits would be vastly outweighed by the time and effort required first have you actually profiled the code doubt that compiling regexes is significant part of the application run time remember that they are only compiled the first time the module is imported in the current execution thereafter the module and its attributes are cached in memory if you have program that basically spawns once compiles bunch of regexes and then exits you could try re engineering it to perform multiple tests in one invocation then you could re use the regexes as above finally you could compile the regexes into based state machines and then link them in with an extension module while this would likely be more difficult to maintain it would eliminate regex compilation entirely from your application
|
QA
|
how to add method using metaclass how do add an instance method to class using metaclass yes do need to use metaclass the following kind of works but the func name will still be foo def bar self print bar class metafoo type def new cls name bases dict dict foobar bar return type name bases dict class foo object metaclass metafoo foo foobar bar foobar func name bar my problem is that some library code actually uses the func name and later fails to find the bar method of the foo instance could do dict foobar types functiontype bar func code foobar there is also types methodtype but need an instance that does nt exist yet to use that am missing someting here
|
think what you want to do is this class foo def init self self def bar self print bar self bar func name foobar foo foobar bar foo foobar bar foobar func name foobar now you are free to pass foos to library that expects foo instances to have method named foobar unfortunately do not know how to use metaclasses and am not sure read your question correctly but hope this helps note that func name is only assignable in python and higher
|
QA
|
how to add method using metaclass how do add an instance method to class using metaclass yes do need to use metaclass the following kind of works but the func name will still be foo def bar self print bar class metafoo type def new cls name bases dict dict foobar bar return type name bases dict class foo object metaclass metafoo foo foobar bar foobar func name bar my problem is that some library code actually uses the func name and later fails to find the bar method of the foo instance could do dict foobar types functiontype bar func code foobar there is also types methodtype but need an instance that does nt exist yet to use that am missing someting here
|
try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods class parent object def bar self print bar class metafoo type def new cls name bases dict return type name parent bases dict class foo object metaclass metafoo if name main foo bar print bar func name
|
QA
|
how create threads under python for delphi am hosting python script with python for delphi components inside my delphi application would like to create background tasks which keep running by script is it possible to create threads which keep running even if the script execution ends but not the host process which keeps going on have noticed that the program gets stuck if the executing script ends and there is thread running however if will wait until the thread is finished everything goes fine am trying to use threading standard module for threads
|
python has its own threading module that comes standard if it helps you can create thread objects using the threading module threading documentation thread documentation the thread module offers low level threading and synchronization using simple lock objects again not sure if this helps since you are using python under delphi environment
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
the real answer to your question is that if you are going to use the language you need to learn its syntax just as an error in indenting python can generate compiler error an error using braces in various other languages can also generate compiler error even worse it can be silently misinterpreted by the compiler to do the wrong thing this is particularly dangerous when the indenting does not match the desired meaning in many other languages if first condition if second condition do something interesting else do something different will lead to unpleasant surprises python forces you to write code that looks like what it does this is good thing for other programmers who have to read your code or for you when you try to read your own code after month or so
|
QA
|
caching compiled regex objects in python each time python file is imported that contains large quantity of static regular expressions cpu cycles are spent compiling the strings into their representative state machines in memory re compile re compile question is it possible to store these regular expressions in cache on disk in pre compiled manner to avoid having to execute the regex compilations on each import pickling the object simply does the following causing compilation to happen anyway import pickle import re re compile pickle dumps cre compile np np ni ntp nrp and re objects are unmarshallable import marshal import re re compile marshal dumps traceback most recent call last file stdin line in module valueerror unmarshallable object
|
the shelve module appears to work just fine import re import shelve pattern pattern re compile pattern re compile pattern shelve open re cache pattern pattern close shelve open re cache pattern pattern close you can then make nice wrapper class that automatically handles the caching for you so that it becomes transparent to the user an exercise left to the reader
|
QA
|
can parallel traversals be done in matlab just as in python using the zip function python allows for loops to traverse multiple sequences in parallel for in zip list list does matlab have an equivalent syntax if not what is the best way to iterate over two parallel arrays at the same time using matlab
|
if and are column vectors you can do for do stuff with and end with row vectors just use and here is an example run for disp size of num str size num str num str end size of size of size of
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
in terms of speed the best cross platform ipc mechanism will be pipes that assumes however that you want cross platform ipc on the same machine if you want to be able to talk to processes on remote machines you will want to look at using sockets instead luckily if you are talking about tcp at least sockets and pipes behave pretty much the same behavior while the apis for setting them up and connecting them are different they both just act like streams of data the difficult part however is not the communication channel but the messages you pass over it you really want to look at something that will perform verification and parsing for you recommend looking at google protocol buffers you basically create spec file that describes the object you want to pass between processes and there is compiler that generates code in number of different languages for reading and writing objects that match the spec it is much easier and less bug prone than trying to come up with messaging protocol and parser yourself
|
QA
|
how do you retrieve items from dictionary in the order that they are inserted is it possible to retrieve items from python dictionary in the order that they were inserted
|
or just make the key tuple with time now as the first field in the tuple then you can retrieve the keys with dictname keys sort and voila gerry
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
if you are willing to try something little different there is the ice platform from zeroc it is open source and is supported on pretty much every os you can think of as well as having language support for java ruby python and php finally it is very easy to drive the language mappings are tailored to fit naturally into each language it is also fast and efficient there is even cut down version for devices
|
QA
|
python cgi on iis how do you set up iis so that you can call python scripts from asp pages ok so found the answer to that question here http support microsoft com kb so on to my next question how do you call cgi script from within classic asp vb code particularly one which is not in the web root directory
|
do not believe that vbscript as hosted by iis has any way of executing an external process if you are using python as an axscripting engine then you could just use the sys module if the script you are calling is actually meant to be cgi script you will have to mimic all the environment variables that the cgi uses the alternative is to put the script on the python path import it and hope that it is modular enough that you can call the pieces you need and bypass the cgi handling code
|
QA
|
decorating parent class method would like to make child class that has method of the parent class where the method is classmethod in the child class but not in the parent class essentially am trying to accomplish the following class foo object def meth self val self value val class bar foo meth classmethod foo meth
|
what are you trying to accomplish if saw such construct in live python code would consider beating the original programmer
|
QA
|
how to setup vim autoindentation properly for editing python files py have troubles setting vim xxx for editing python files indenting seems to be broken optimal spaces have followed some tutorials found via google still no effect please help
|
ensure you are editing the correct configuration file for vim especially if you are using windows where the file could be named vimrc instead of vimrc as on other platforms in vim type help vimrc and check your path to the vimrc vimrc file with echo home echo vim make sure you are only using one file if you want to split your configuration into smaller chunks you can source other files from inside your vimrc file help source
|
QA
|
caching compiled regex objects in python each time python file is imported that contains large quantity of static regular expressions cpu cycles are spent compiling the strings into their representative state machines in memory re compile re compile question is it possible to store these regular expressions in cache on disk in pre compiled manner to avoid having to execute the regex compilations on each import pickling the object simply does the following causing compilation to happen anyway import pickle import re re compile pickle dumps cre compile np np ni ntp nrp and re objects are unmarshallable import marshal import re re compile marshal dumps traceback most recent call last file stdin line in module valueerror unmarshallable object
|
open usr lib python re py and look for def compile you will find re py internal cache mechanism
|
QA
|
decorating parent class method would like to make child class that has method of the parent class where the method is classmethod in the child class but not in the parent class essentially am trying to accomplish the following class foo object def meth self val self value val class bar foo meth classmethod foo meth
|
am also not entirely sure what the exact behaviour you want is but assuming its that you want bar meth to be equivalent to foo meth being classmethod of bar with self being the class then you can acheive this with def convert to classmethod method return classmethod method im func class bar foo meth convert to classmethod foo meth the problem with classmethod foo meth is that foo meth has already been converted to method with special meaning for the first parameter you need to undo this and look at the underlying function object reinterpreting what self means would also caution that this is pretty odd thing to do and thus liable to cause confusion to anyone reading your code you are probably better off thinking through different solution to your problem
|
QA
|
how do create new signal in pygtk have created python object but want to send signals on it made it inherit from gobject gobject but there does not seem to be any way to create new signal on my object
|
here is how import gobject class mygobjectclass gobject gobject gobject signal new signal name mygobjectclass gobject signal run first none str int where the second to last argument is the return type and the last argument is tuple of argument types
|
QA
|
nice python wrapper for yahoo geoplanet web service has anybody created nice wrapper around yahoo geo webservice geoplanet yet
|
after brief amount of googling found nothing that looks like wrapper for this api but am not quite sure if wrapper is what is necessary for geoplanet according to yahoo documentation for geoplanet requests are made in the form of an http get messages which can very easily be made using python httplib module and responses can take one of several forms including xml and json python can very easily parse these formats in fact yahoo itself even offers libraries for parsing both xml and json with python know it sounds like lot of libraries but all the hard work has already been done for the programmer it would just take little gluing together and you would have yourself nice interface to yahoo geoplanet using the power of python
|
QA
|
decorating parent class method would like to make child class that has method of the parent class where the method is classmethod in the child class but not in the parent class essentially am trying to accomplish the following class foo object def meth self val self value val class bar foo meth classmethod foo meth
|
the question as posed seems quite odd to me cannot see why anyone would want to do that it is possible that you are misunderstanding just what classmethod is in python it is bit different from say static method in java normal method is more or less just function which takes as its first argument usually called self an instance of the class and which is invoked as classmethod is more or less just function which takes as its first argument often called cls class and which can be invoked as or as with this in mind and your code shown above what would you expect to have happen if someone creates an instance of bar and calls meth on it bar bar bar meth xyz when the code to meth is called it is passed two arguments self and val guess that you expect xyz to be passed for val but what are you thinking gets passed for self should it be the bar instance in this case no override was needed or should it be the class bar what then would this code do
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
am fairly new to python but the tuple technique seems very pythonic to me however have had another idea that may enhance readability using dictionary allows access to the different values by name rather than position for example def divide return quotient remainder answer divide print answer quotient print answer remainder
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
would just use if elif else statements think that it is good enough to replace the switch statement
|
QA
|
serving dynamically generated zip archives in django how to serve users dynamically generated zip archive in django am making site where users can choose any combination of available books and download them as zip archive am worried that generating such archives for each request would slow my server down to crawl have also heard that django does not currently have good solution for serving dynamically generated files
|
cannot you just write link to zip server or whatnot why does the zip archive itself need to be served from django era cgi script to generate zip and spit it to stdout is really all that is required here at least as far as can see
|
QA
|
serving dynamically generated zip archives in django how to serve users dynamically generated zip archive in django am making site where users can choose any combination of available books and download them as zip archive am worried that generating such archives for each request would slow my server down to crawl have also heard that django does not currently have good solution for serving dynamically generated files
|
django does not directly handle the generation of dynamic content specifically zip files that work would be done by python standard library you can take look at how to dynamically create zip file in python here if you are worried about it slowing down your server you can cache the requests if you expect to have many of the same requests you can use django cache framework to help you with that overall zipping files can be cpu intensive but django should not be any slower than another python web framework
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
you might want to try yami it is very simple yet functional portable and comes with binding to few languages
|
QA
|
project structure for google app engine started an application in google app engine right when it came out to play with the technology and work on pet project that had been thinking about for long time but never gotten around to starting the result is bowlsk however as it has grown and features have been added it has gotten really difficult to keep things organized mainly due to the fact that this is my first python project and did not know anything about it until started working what have main level contains all py files did not know how to make packages work all html templates for main level pages subdirectories separate folders for css images js etc folders that hold html templates for subdirecty type urls example http www bowlsk com maps to homepage default package template at index html http www bowlsk com games view series html series maps to viewseriespage again default package template at games view series html it is nasty how do restructure had ideas main folder containing appdef indexes main py subfolder for code does this have to be my first package subfolder for templates folder heirarchy would match package heirarchy individual subfolders for css images js etc main folder containing appdef indexes main py subfolder for code templates this way have the handler class right next to the template because in this stage am adding lots of features so modifications to one mean modifications to the other again do have to have this folder name be the first package name for my classes would like the folder to be src but do not want my classes to be src whateverpage is there best practice with django on the horizon is there something can do now to improve my ability to integrate with it when it becomes the official gae templating engine would simply start trying these things and seeing which seems better but pydev refactoring support does not seem to handle package moves very well so it will likely be non trivial task to get all of this working again
|
think the first option is considered the best practice and make the code folder your first package the rietveld project developed by guido van rossum is very good model to learn from have look at it http code google com rietveld with regard to django suggest you start using the django trunk code instead of the gae built in django port again have look at how it is done in rietveld
|
QA
|
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
|
believe you can use imp find module and imp load module to load the specified module you will need to split the module name off of the path if you wanted to load home mypath mymodule py you would need to do imp find module mymodule home mypath but that should get the job done
|
QA
|
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
|
for python use import importlib util spec importlib util spec from file location module name path to file py foo importlib util module from spec spec spec loader exec module foo foo myclass for python and use from importlib machinery import sourcefileloader foo sourcefileloader module name path to file py load module foo myclass although this has been deprecated in python python use import imp foo imp load source module name path to file py foo myclass there are equivalent convenience functions for compiled python files and dlls see also http bugs python org issue
|
QA
|
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
|
you can use the load source module name path to file method from imp module
|
QA
|
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
|
import package modules at runtime python recipe http code activestate com recipes classloader py import sys types def get mod modulepath try amod sys modules modulepath if not isinstance amod types moduletype raise keyerror except keyerror the last is very important amod import modulepath globals locals sys modules modulepath amod return amod def get func fullfuncname retrieve function object from full dotted package name parse out the path module and function lastdot fullfuncname rfind you funcname fullfuncname lastdot modpath fullfuncname lastdot amod get mod modpath afunc getattr amod funcname assert that the function is callable attribute assert callable afunc you is not callable fullfuncname return reference to the function itself not the results of the function return afunc def get class fullclassname parentclass none load module and retrieve class not an instance if the parentclass is supplied classname must be of parentclass or subclass of parentclass or none is returned aclass get func fullclassname assert that the class is subclass of parentclass if parentclass is not none if not issubclass aclass parentclass raise typeerror you is not subclass of fullclassname parentclass return reference to the class itself not an instantiated object return aclass usage class storagemanager pass class storagemanagermysql storagemanager pass def storage object afullclassname alloptions astoreclass get class afullclassname storagemanager return astoreclass alloptions
|
QA
|
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
|
you can also do something like this and add the directory that the configuration file is sitting in to the python load path and then just do normal import assuming you know the name of the file in advance in this case config messy but it works configfile config py import os import sys sys path append os path dirname os path expanduser configfile import config
|
QA
|
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
|
do you mean load or import you can manipulate the sys path list specify the path to your module then import your module for example given module at foo bar py you could do import sys sys path foo puts the foo directory at the start of your path import bar
|
QA
|
how do create new signal in pygtk have created python object but want to send signals on it made it inherit from gobject gobject but there does not seem to be any way to create new signal on my object
|
you can also define signals inside the class definition class mygobjectclass gobject gobject gsignals some signal gobject signal run first gobject type none object the contents of the tuple are the the same as the three last arguments to gobject signal new
|
QA
|
when to create new app with startapp in django have googled around for this but still have trouble relating to what django defines as apps should create new app for each piece of functionality in site even though it uses models from the main project do you guys have good rule of thumb of when to split off new app and when to keep functionality together with the main project or other apps
|
an app could be many different things it all really comes down to taste for example let us say you are building blog your app could be the entire blog or you could have an admin app site app for all of the public views an rss app services app so developers can interface with the blog in their own ways etc personally would make the blog itself the app and break out the functionality within it the blog could then be reused rather easily in other websites the nice thing about django is that it will recognize any models py file within any level of your directory tree as file containing django models so breaking your functionality out into smaller sub apps within an app itself will not make anything more difficult
|
QA
|
why might my pyglet vertex lists and batches be very slow on windows am writing opengl code in python using the library pyglet when draw to the screen using pyglet graphics vertex list or pyglet graphics batch objects they are very slow fps compared to plain old pyglet graphics draw or just glvertex calls which are about fps for the same geometry in linux the vertex list is about the same speed as glvertex which is disappointing and batch methods are about twice as fast which is little better but not as much gain as was hoping for
|
do not know personally but noticed that you have not posted to the pyglet mailing list about this more pyglet users as well as the primary developer read that list
|
QA
|
how to setup vim autoindentation properly for editing python files py have troubles setting vim xxx for editing python files indenting seems to be broken optimal spaces have followed some tutorials found via google still no effect please help
|
for more advanced python editing consider installing the simplefold vim plugin it allows you do advanced code folding using regular expressions use it to fold my class and method definitions for faster editing
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
if you do not want to use an ide text editor with automatic indenting you can use the pindent py script that comes in the tools scripts directory it is preprocessor that can convert code like def foobar if elif if end if else print oops end if end def foobar into def foobar if elif if end if else print oops end if end def foobar which is valid python
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
emacs seriously its use of tab is command not character is absolutely perfect for python development
|
QA
|
when to create new app with startapp in django have googled around for this but still have trouble relating to what django defines as apps should create new app for each piece of functionality in site even though it uses models from the main project do you guys have good rule of thumb of when to split off new app and when to keep functionality together with the main project or other apps
|
the rule follow is it should be new app if want to reuse the functionality in different project if it needs deep understanding of the models in your project it is probably more cohesive to stick it with the models
|
QA
|
what python way would you suggest to check whois database records am trying to get webservice up and running that actually requires to check whois databases what am doing right now is ugly and would like to avoid it as much as can call gwhois command and parse its output ugly did some search to try to find pythonic way to do this task generally got quite much nothing this old discussion list link has way to check if domain exist quite not what was looking for but still it was best anwser google gave me everything else is just bunch of unanwsered questions any of you have succeeded to get some method up and running would very much appreciate some tips or should just do it the opensource way sit down and code something by myself
|
do not know if gwhois does something special with the server output however you can plainly connect to the whois server on port whois send your query read all the data in the reply and parse them to make life little easier you could use the telnetlib telnet class even if the whois protocol is much simpler than the telnet protocol instead of plain sockets the tricky parts which whois server will you ask ripe arin apnic lacnic afrinic jpnic verio etc lacnic could be useful fallback since they tend to reply with useful data to requests outside of their domain what are the exact options and arguments for each whois server some offer help others do not in general plain domain names work without any special options
|
QA
|
why do you need explicitly have the self argument into python method when defining method on class in python it looks something like this class myclass object def init self self self but in some other languages such as you have reference to the object that the method is bound to with the this keyword without declaring it as an argument in the method prototype was this an intentional language design decision in python or are there some implementation details that require the passing of self as an argument
|
it is to minimize the difference between methods and functions it allows you to easily generate methods in metaclasses or add methods at runtime to pre existing classes class object def foo self print hi def bar self print bork bork bork bar bar bar bork bork bork foo hi it also as far as know makes the implementation of the python runtime easier
|
QA
|
why do you need explicitly have the self argument into python method when defining method on class in python it looks something like this class myclass object def init self self self but in some other languages such as you have reference to the object that the method is bound to with the this keyword without declaring it as an argument in the method prototype was this an intentional language design decision in python or are there some implementation details that require the passing of self as an argument
|
like to quote peters zen of python explicit is better than implicit in java and this can be deduced except when you have variable names that make it impossible to deduce so you sometimes need it and sometimes do not python elects to make things like this explicit rather than based on rule additionally since nothing is implied or assumed parts of the implementation are exposed self class self dict and other internal structures are available in an obvious way
|
QA
|
how to copy file to remote server in python using scp or ssh have text file on my local machine that is generated by daily python script run in cron would like to add bit of code to have that file sent securely to my server over ssh
|
if you want the simple approach this should work you will want to close the file first so you know it is flushed to disk from python import os os system scp file user server path os system scp foo bar joe srvr net path to foo bar you need to generate on the source machine and install on the destination machine an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key in other words so your script does not ask for password ssh keygen example
|
QA
|
how to copy file to remote server in python using scp or ssh have text file on my local machine that is generated by daily python script run in cron would like to add bit of code to have that file sent securely to my server over ssh
|
you would probably use the subprocess module something like this import subprocess subprocess popen scp myfile destination sts os waitpid pid where destination is probably of the form user remotehost remotepath thanks to charles duffy for pointing out the weakness in my original answer which used single string argument to specify the scp operation she will true that would not handle whitespace in paths the module documentation has examples of error checking that you may want to perform in conjunction with this operation ensure that you have set up proper credentials so that you can perform an unattended passwordless scp between the machines there is stackoverflow question for this already
|
QA
|
change command method for tkinter button in python create new button object but did not specify the command option upon creation is there way in tkinter to change the command onclick function after the object has been created
|
sure just use the bind method to specify the callback after the button has been created have just written and tested the example below you can find nice tutorial on doing this at http www pythonware com library tkinter introduction events and bindings htm from tkinter import tk button root tk button button root text click me button pack def callback event print hello world button bind button callback root mainloop
|
QA
|
why do you need explicitly have the self argument into python method when defining method on class in python it looks something like this class myclass object def init self self self but in some other languages such as you have reference to the object that the method is bound to with the this keyword without declaring it as an argument in the method prototype was this an intentional language design decision in python or are there some implementation details that require the passing of self as an argument
|
python does not force you on using self you can give it whatever name you want you just have to remember that the first argument in method definition header is reference to the object
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.