[Tutor] Tutor list as pair progamming plush toy
Have you ever got that piece of advice about - when you have stuck on a bug you seem unable to track - getting a plush toy to whom you explain your code? (This is of course a workaround if you do not have a fellow developer to help you out). Well... I found out this advice kind of works for me, with the notable difference that my plush toy is this mailing list. It works so wonderfully that indeed is several months I do not post any message: whenever I get stuck, I begin to write a message to the list, and in the process of explaining what is the intended behaviour and outcome of my code, I systematically find the bug by myself. I know - this is slightly OT for the list - but I thought to share as maybe this is a "hidden benefit" the list is bringing to a few people without the tutors even knowing it. Does anybody else experience the same? Cheers, :) Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] xml question
On Mon, 2010-07-26 at 12:09 -0700, Albert-Jan Roskam wrote: > I am making a data processing program that will use a configuration > file. The file should contain information about: (1) source files > used, (2) (intermediate) output files, (3) used parameters/estimation > methods (4) manual data edits + datetime stamp + user name . I'd like > to store this config file in xml. However, I've never created > something like this before. Is this a suitable format, and, if so, > what would the elementtree look like? Should I just use 'config' or > something similar as root, and the information elements 1 through 3 as > child elements? And should the manual edits be stored as an element > 'edit' with various attributes (the edit itself, the time stamp, > etc.)? I am with Steven on the fact that XML might not necessarily be the best choice, unless you plan to use the configuration file with other third-party programs, in which case the fact that XML has built-in parsing libs for nearly all languages makes life of fellow developer easier. For the next project of mines, I am planning to use YAML (YAML Ain't a Markup Language). I stumbled upon this format while toying around with the google app engine, that uses it for storing your application configuration data. IMO, YAML has the following prominent advantages: 1) It is easy to read and edit by humans [think "markdown"] 2) It has solid parsing libraries for Python 3) It is far less verbose than XML 4) It is consistent with Python "relevant whitespaces" [indentation is used to define data structure hierarchy] I have not yet got to the stage of writing code that use YAML (will take two more weeks at best for me to get to that point), but should you go down this road, I would love to hear back from you. [As I would love to hear from anybody else who might have experience with YAML+Python] Some links: - http://en.wikipedia.org/wiki/YAML [good overview of the format] - http://www.yaml.org/ [official site... when consistency with the format makes a website hard to browse!] - http://pyyaml.org/wiki/PyYAMLDocumentation [documentation of the library for Python - pure Python code // can use a C library] An example of YAML file to give you the taste of it: > receipt: Oz-Ware Purchase Invoice > date:2007-08-06 > > customer: > given: Dorothy > family: Gale > > items: > - part_no: A4786 > descrip: Water Bucket (Filled) > price: 1.47 > quantity: 4 > - part_no: E1628 > descrip: High Heeled "Ruby" Slippers > price: 100.27 > quantity: 1 > > bill-to: &id001 > street: | > 123 Tornado Alley > Suite 16 > city: East Westville > state: KS > > ship-to: *id001 > > specialDelivery: > > Follow the Yellow Brick > Road to the Emerald City. > Pay no attention to the > man behind the curtain. HTH, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] django help....
On Mon, 2010-07-26 at 14:03 +0100, Dipo Elegbede wrote: > what ook would you recommend for a beginner? I am a django beginner myself. I did the tutorial first (http://docs.djangoproject.com/en/dev/intro/tutorial01/) and now I am very happy with "Practical Django Projects": http://www.amazon.com/Practical-Django-Projects-Experts-Development/dp/1430219386 I assume that the fact I have a bit more than a year of "fooling around" with Python (2.x series) makes this book easy to follow. If you contrarily are not familiar with Python syntax then it might not be the best choice. As already mentioned by others, the Django book (http://djangobook.com) is also a an excellent (and free!) alternative. I've also begun to read "Pro Django" (http://prodjango.com/), which is another excellent book, providing material to learn to leverage Python itself better (beside Django). However - to put it as its author does - "Pro Django isn’t for the faint of heart. It’s not for people who are new to Django, and especially not those who are new to Python". Best luck with your learning! Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lambda vs list comp
On Tue, 2010-07-27 at 09:44 -0700, Jon Crump wrote: > Just as a matter of curiosity piqued by having to understand someone > else's code. Is the difference here just a matter of style, or is one > better somehow than the other? > > >>> l > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > >>> ','.join([str(x) for x in l]) > '0,1,2,3,4,5,6,7,8,9,10' > > >>> ','.join(map(lambda x:str(x), l)) > '0,1,2,3,4,5,6,7,8,9,10' Considering that "readability metters" I would go for none of the two, but for: ','.join(map(str, l)) (Indeed defining a lambda function that simply uses "str" is redundant) Just my personal take on this, though! Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calculating and returning possible combinations of elements from a given set
On Tue, 2010-07-27 at 23:31 +0100, Mark Lawrence wrote: > On 27/07/2010 23:20, ZUXOXUS wrote: > > Hi all pythoners > > > > I've got a probably easy to answer question. > > > > Say I've got a collections of strings, e.g.: 'man', 'bat', 'super', 'ultra'. > > > > They are in a list, or in a sequence or whatever, say a bag of words > > > > And now I want to know how many couples I can do with them, and I want the > > program to show me the actual couples: 'manman', 'manbat', 'mansuper', > > 'manultra', 'batbat', 'batman', 'batsuper', etc. > > > > But hey, why building up new words from just two strings? I also want to > > know the possible combinations of three words, four words, and perhaps, why > > not, five words. > > > > So, is it easy to do? > > > > Sorry, I'm new in programing, and am probably far from being a math-master > > > > I'm clueless, I think probably the code have some FOR I IN SEQUENCE... but > > then what? I don't know how to say: take every element and paste it to > > another one from the bag, and with another one, and with another one,... > > > > If it's too complex, I dont need the whole code recipe, just need some > > clues, or perhaps a useful link > > > > Thank you very much in advance! > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > The lazy way. > http://docs.python.org/library/itertools.html > Look for combinations(). >From the examples listed by the OP (see: "manbat", "batman") I actually believe he is looking for the cartesian product. The syntax should therefore be (DISCLAIMER: I am going by memory without having the possibility of testing right now): import itertools for prod in itertools.product(my_list_of_words, 2): print prod (The two as second parameter tells that you are wishing to have a bi-dimensional product, with both axis having the same list of words. See docs for more info) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Plugin system - how to manage plugin files?
Hi everybody, This is more of a python software design question rather than a question on the Python syntax alone. I hope it is fine to ask here. I am working on a small project, that I will release under a GPL license, whose main design guiding principle is extensibility. Thus I am trying to make as easy as possible for other devs to create plugins. I implemented my plugin system by defining a metaclass, that register - with a class method - the class name of any plugin that gets loaded (all plugins inherit from a class defined in the core code). Basically this means that a developer will have to define his class as: class PluginMyName(MotherOfAllPlugins) do_stuff_here And the main program will know of his presence because "PluginMyName" will be included in the list available at "MotherOfAllPlugins.plugins". Being the mounting method a class method, all plugins get registered when their class code is loaded into memory (so even before an object of that class is instantiated). The system works good enough for me (although I am always open to suggestions on how to improve the architecture!) but I am now wondering what would be the best way to manage the plugin files (i.e. where and how the files containing the plugins should be stored). So far I am using - for developing purposes - a package that I called "plugins". I put all my pluginX.py files in the package directory and I simply have to issue "import plugins" in the main.py file, for all the plugins to get mounted properly. However this system is only good while I am developing and testing the code, as: 1. Plugins might come with their own unittests, and I do not want to load those in memory. 2. All plugins are currently loaded into memory, but indeed there are certain plugins which are alternative versions of the same feature, so you really just need to know that you can switch between the two, but you want to load into memory just one. 3. At some point, I will want to have a double location for installing plugins: a system-wide location (for example /usr/local/bin/) and a user-specific one (for example /home//.myprogram/). So my questions are really - perhaps - three: 1) What is the most sensible format for the plugin code (a file? a package? A simple directory of files?) 2) Which is a smart way to use Python introspection to recognise the presence of plugins without necessarily loading (importing) them. 3) Is there a standard way / best practice (under gnu/linux, at least) to allow for plugins to be placed in two different locations? Thank you in advance for your time and guidance, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Plugin system - how to manage plugin files?
On Wed, 2010-07-28 at 13:53 -0500, Scott Nelson wrote: > On Wed, Jul 28, 2010 at 10:07 AM, Mac Ryan > wrote: > Hi everybody, > > > Mac, > > I don't know if this is exactly what you are after, but I created a > poor-man's plugin system by simply putting .py files into the same > directory as my app and naming them like _plugin.py Each of > these .py "plugins", had to define a class named "Plugin" that had > some set of expected methods and properties (ex: initialize(), run(), > etc.). Then, when my app started up, it simply got a list of all the > "*_plugin.py" files in the current directory, dynamically imported the > files using "my_module = __import__(name)" and then I could do > whatever I wanted with that module using "my_module", such as > instantiate an object for each module's "Plugin" class, etc. > > Actually, here's a snippet of code I had lying around that I slapped > together a few years ago to remind myself of how I did this. I can't > promise this is 100% tested, but it should give you an idea. > > http://pastebin.com/UtVp6J9j > > Also, you might want to look at this discussion: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ba8d361516403fdf/ > > Best of luck! > > -Scott Thank you Scott for your reply, I inspected the code you pastebin'd, but I am under the impression the solution you proposed present about the same shortcomings that mines... I recognise that the naming convention of files solve the problem of having in the same place files which might not be plugins, but the naming convention is an imposition that I would rather try not to impose to other devs, the reson being that in my application plugins get subclassed, so that - if the name of the plugin must be relevant - names would end up being something like: medianvalues_gtk_statistics_scores_plugin.py where "medianvalues" would be the name of the plugin, an each other underscore-separated word would be a parent class. My hope is that somebody will show me some "automagic obscure voodoo method" (I am thinking to some "__real_vooodoo__" method or function somewhere in the module file or in the __init__.py file of the packages) that will be able to provide information on the plugin without actually loading it... Let's see if somebody else will reply to this [admittedly not-so-popular] thread! ;) Mac. PS: About the thread that you linked in your reply: my solution is in the line of what Fredrik Lundh proposed, using __metaclass___ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with subprocess
On Fri, 2010-07-30 at 14:36 +0200, Bala subramanian wrote: > I have to do a series of job in a remote machine. I put each job in a > text file called 'job' as and wrote the following code that can read > each line in the text file and execute the job. If that works for you, no need to change it, of course. Just wondered - however - if you are aware that there is a python library that just do that (remote machine management). It's called "fabric": >From the official docs: "Fabric is a Python library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks. It provides a basic suite of operations for executing local or remote shell commands (normally or via sudo) and uploading/downloading files, as well as auxiliary functionality such as prompting the running user for input, or aborting execution. Typical use involves creating a Python module containing one or more functions, then executing them via the fab command-line tool." http://docs.fabfile.org/0.9.1/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where to start with Unit Testing
On Sun, 2010-08-01 at 03:30 -0400, Huy Ton That wrote: > Hi all, > > Do any of you have any feedback, strategies and best practices related > to unit testing within Python. This is a relatively new topic for me. > I was thinking of starting with reading the documentation associate > with the unittest module. My answer falls in the category "feedback" (I was also going to mention the diveintopython page, but somebody else has done that already!), so you should be aware what follows is highly subjective... JUST THINK... IN PYTHON! IMO, unit testing is really easy to pick up. It really does not amount to much more than taking note (in python) of what you are thinking when you are coding. If you are anything like me, when you code you keep on formulating "rules" in your head, in the line of "when everything works as expected, if the methods iterates four times, then this method must return X" or "when everything works as expected, if a user enter a value over 212 then the script must throw this exception", etc... * the "when everything works as expected" translates in "this test pass when..." * the "if X" translates in your test case (i.e. the scenario you are testing for) * the "then Y" translates in "the outcome of my test case must be Y" TESTING IS VALUABLE IN THE LONG RUN At times, designing and coding a test is a time-consuming activity, and if the code is particularly straightforward you might be tempted to skip the unit testing altogether. In my experience - however - unit testing is never as useful on the spot as it is three months from now, when you will have/want/choose to modify a little bit of your old code, and all of a sudden everything will break. In the latter scenario, your test suite will be an invaluable asset. FUNCTIONAL PROGRAMMING WINS The most difficult thing in writing a test, is replicating the state of the environment needed for the test to happen. This is especially (but not uniquely) true for DB-driven applications, when you might wish to perform test on methods that interact with the DB. In that case you have to create a test DB, populate it with ~credible data, etc... The most "functional" (as in functional programming, i.e. machine-state independent) is your code, the easiest is to write a test. Example: if you need to check a method that validate the postal code of an address based on the name of the city, it is easier to test a method that is invoked with "validate_postal_code(code, city)" rather than one that is invoked with "validate_postal_address(user)" and that will have to retrieve the full address of a user from a DB, and extract the city and postal address from it. MVC WINS I never test UI's. I know it is bad... but it is simply too time-consuming for me (I'll be very glad if somebody reading this will show me how one can make it snappier!). This means - at least for me - that writing tests become extremely easier for me if I keep separated the presentation layer from all the rest of the stuff. EVERY BUG IS A TEST YET NOT WRITTEN A program that passes all its tests is not necessarily a bug-free program. But once you find a new bug, try to make a point of writing a new test that check for that particular scenario in which said bug is happening. TEST-DRIVEN IS BETTER What I find useful (although not always applicable) is to start my programming session by writing the tests before I write the code to be tested. This somehow reconnect to my previously articulated "just think... in python!" point: you are however *already doing a list of rules* in your head, before writing code, so you could well write it down directly in code. All you need is to create a mock method/function in your code with the same signature you are using in your test. For example. You could write tests in the form: assertEqual(better_square_root(9), 3) assertRaises(ValueError, better_square_root, -4) and then write in your module: def my_better_square_root(number): pass all your tests will of course initially fail, but then you will keep on working on the code of my_better_square_root until all your tests pass. Well, these are just my two ¢... As stated in the beginning: highly subjective, so keep your mind open for other (possibly opposite) opinions too! :) HTH, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where to start with Unit Testing
> A different analogy comes to my mind; I once saw two different sets of > people analyze data. One did it "by hand": visually inspecting > thousands > of signals herself and typing Y or N to accept or reject each signal. > The > other did it with an automated system that accepted or rejected > signals > based on fuzzy logic. In an important interpretation, the automated > system > was far better, and yet the first scientist was done with her analysis > and > accepted for publication before the second team even had the bugs > worked > out of the automated system! Yes, I think the slow-but-more-proper > team > did the more correct thing, but there is something to be said for > "good > enough", too (it works for evolution, for example). Che, from the analogies you made, it looks like you might not have very clear what Unit Testing is for. True, UT is a way to automate tests that otherwise you should do manually (as per your analogy), but the test you automate with UT are not a "one off" thing (as it is processing the data needed to publish a paper): depending on the coding philosophy you follow, you might run UT as often as every couple of hours of coding (as it is in certain agile programming techniques). UT is there to give you a tool to prevent regression *when/if you modify or refactor your code* (which is the norm if you are a professional programmer), and its advantages grow exponentially with the increase of complexity of the code and the increase of number of developers working on the project (it is very easy to break someone's else code... there is a reason for which "blame" - http://blame.sourceforge.net/ - is called that way!). If you are an hobbyist programmer busy on a simple one-off small app, you may skip UT altogether, manually inspect the behaviour of your program, and never regret it. But if you are writing an e-commerce application that will organise transaction for millions of euros of revenue monthly, UT is probably the very first code you will want to commit to your repo. Mac. PS: I did not comment on the analogy with evolution, because did not get the parallelism you were trying to draw. Care to explain? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where to start with Unit Testing
On Mon, 2010-08-02 at 11:59 -0400, Che M wrote: > Mac, I found this an excellent brief overview of UT and your points > all > seem very strong to me. Thanks very much. I admit I didn't really > know > anything about the topic and was mentioning my feelings on the matter > partly to elicit enlightening responses like this (maybe because I was > feeling > like I was being irresponsible with my own project by not learning UT > and running tests). > > I am in the "hobbyist programmer busy on a simple one-off small app" > camp ("simple" is relative...though it is clearly nothing like a big > e-commerce application!), so I feel OK with foregoing getting into UT > for now. If things get more complex and I at some point have actual > users > instead of the large number of vapor users I have now (:D) I may > buckle > down and learn it. No worries than, I am happy my answer was of some use. Unit testing in python is however very very easy to use in a great number of situations, so don't be scared to get your hands dirty with it! A few days back I read this sentence: "Later than you expected, but sooner than you think" which in the context meant that we tend to over-estimate our abilities prior to start something new, but than - once we started working on it, we contrarily under-estimate our ability to achieve quickly a good level of performance... Happy learning! :) Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] argparse: how to use the returned Namespace object?
Hi, I'm writing a small command line utility using the argparse module (I am on python 2.6.6 so that's not in the standard lib, but this should not play any role in my problem, I believe). My goal is to use a class that I already wrote and cannot change for a GUI app, as a command utility, so I would like to simply have the CLI as a wrapping layer, without changing the pre-existing code. The code I want to reuse, accept all keywords arguments, so I wrote my parser in such a way that it returns keywords/values in a compatible way to my method signatures. Example: Let the signature of one of my functions be: def do_stuff(overwrite=False, verbose=False): do-some-stuff-here I wrote the parser in such a way that issuing: utilityname dostuff --overwrite --verbose I get at the end of the parsing process a variable "args" that looks like this: Namespace(command=dostuff, overwrite=True, verbose=True) Now, I tried to do the following: command = args.command del args.command command(**args) But that doesn't work because the Namespace implementation of the argparse result is an object which is not iterable. Of course if I use: args.command(overwrite=args.overwrite, verbose=args.verbose) I get the system working, but the fact is that each command calls a different function / method, each of them with a different signature. My question boils down to: how can I expand the Namespace object in order to get a list of keyword arguments? Thank you for your time, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] argparse: how to use the returned Namespace object?
On Fri, 2010-11-05 at 00:17 +, Walter Prins wrote: > > > On 4 November 2010 23:20, Mac Ryan wrote: > My question boils down to: how can I expand the Namespace > object in > order to get a list of keyword arguments? > > If "ns" is your Namespace object, then use ns.__dict__, which you can > directly pass to your commands, e.g. > > do_stuff(**ns.__dict__) > > I'll post a more complete answer if this isn't clear/obvious. > > HTH Thank you Walter. I got it and it works! :) I have a follow-up question, though. I had previously already inspected "ns.__dict__" with the "dir()" function, but couldn't (and can not) see my parameters neither with "dir(ns.__dict__)" nor with "dir(ns.__dict__.items)". This is clearly an indication that I misunderstand what the __dict__ is and how it works. Yet if I do a dir() on an instance of an object, it does work as expected, returning all attributes of that object. Could you (on anybody else!) help me undertand what I fail to grasp? Thank you! Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] argparse: how to use the returned Namespace object?
On Fri, 2010-11-05 at 01:11 +, Walter Prins wrote: > You need to distinguish between what __dict__ *is*, and what it > *contains*. dir() does introspection, it inspects what an object in > Python *is*, e.g. displays all the methods and attributes of the > object. It does not however know anything about what (if anything) > the object might contain, in the data storage sense. [...] Thank you Walter, now I got it. :) Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Too different 2.6 vs 2.7?
On Mon, 2010-11-08 at 17:16 -0800, Terry Carroll wrote: > The only feature I'm pining for at all is the new argparse; but it > depends on your needs. Ubuntu 10.10 here (running python 2.6.6) I use argparse without any problems: I believe the difference between 2.6 and 2.7 [I am not an expert on the subject, so correct me if I am wrong] is that with 2.7 argparse comes as *part of the standard library*, but the library per-se exists since some time, is in the repo, and can be used normally also in previous versions of python, once installed on the system. Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] variable numbers of for loops
On Tue, 23 Nov 2010 13:16:46 + Jose Amoreira wrote: > I read somewhere that for any recursive algorithm there is a > sequential one that is equivalent > [...] > Is there a more straightforward way of solving my specific problem > or, better yet, a general solution to the need of a variable number > of for loops? I am not 100% sure I got the terms of your problem and I am neither an official tutor of this list, so disregard my comment if it is irrelevant... ...yet, the way I normally understand the first sentence I quoted is that any recursive solution can be written iteratively, or in other words "flat" (i.e. having the same procedure called by the main program X number of times, rather than having the procedure calling itself, so effectively nesting itself X number of times). The code you wrote generates programs like: for l0 in alphabet: for l1 in alphabet: for l2 in alphabet: word = "".join([eval("l"+str(i)) for i in range(n)]) listOfWords.append(word) which are recursive in essence (although the recursion is hard-coded rather than dynamic). This is not bad (problems in the domain of combinatorics - like yours - get normally solved recursively) but I can't imagine what would the advantage of this code over dynamic recursion. As for a more straightforward way to solve your specific problem: I would suggest you take a look to the combinatoric generators in the itertools module (http://docs.python.org/library/itertools.html). HTH at least a bit! Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IDEs
On Tue, 23 Nov 2010 15:02:27 +0100 "Josep M. Fontana" wrote: > Does anybody know of any good reference on testing? How do you develop > tests for functions? I haven't found much information on this in the > Python books I own. When I first learnt python I found the "Dive into Python" section of the book rather well done: http://diveintopython.org/unit_testing/index.html If you have the patience to look in the ML archives you will also find some good thread about unit testing there. HTH, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IDEs
On Wed, 24 Nov 2010 01:15:48 - "Alan Gauld" wrote: > In a recent project that we > completed we had 600k lines of production code and over a > million lines of test code. > > And we still wound up with over 50 reported bugs during Beta test... > But that was much better than the 2000 bugs on an earlier project :-) > But testing is hard. Somewhere I read a quote that I liked a lot because IMO it perfectly summarise the idea of test-driven development. Here it is: "Every bug is a test not yet written". Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Need to be pointed in the right direction for file organisation.
Hello everybody, I am new to python programming, but - thanks to "dive into python" - I had no difficulties in picking up the basics of the language and experimenting on my own with PyGTK and STORM. While I am working my way up to a more pythonic and cleaner style in the code, one thing that I have very confused ideas about is how I should organise my code, in terms of classes and files. I read and understood the basic definitions of module and packages (as explained in the abovementioned book) but yet now that I am developing a GUI application with PyGTK I found myself very confused on how I should best organise my code across various files. I would be very grateful if some of the fellow subscribers would take the time to point me out in the right direction. Don't hold back those answers that you might think are too obvious: I am very new to the topic so it might well be that what I miss is some broad concept, rather than some advanced very specific "trick" in the domain of PyGTK apps. Thanks in advance for your time and support, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need to be pointed in the right direction for file organisation.
Thank you Alan for the prompt reply, > - Put reusable components into modules. OK: the use of files as "libraries" is quite clear to me and indeed I am already doing that. What is not clear is if I should _only_ put in modules stuff that is reusable, or if there are other widely accepted ways to user files. For example, in the GTK application I am currently developing I have a notebook widget (sort of tabbed windows which are visible only one at a time). I was therefore thinking about separating the classes for each "tabbed window" in different files, under the impression that this would make the program faster / with a smaller memory footprint, as only the needed file will be loaded into memory [In PHP you can reach quite a gain in terms of speed if yo do so]. Would this be considered a proper way to code in python? Another concern of mine was the readability of the source code, and I was wondering indeed if there was a "pythonic style" that was commonly understood as "the right one" [I'm thinking to those kind of guidelines like "put the import directive at the top of the file", but for file organisation] > - Build modules "bottom up" so that depenedencies tend to > go one way, with higher level modules importing lower level ones. I'm not sure I got it completely, does this mean that the file structure should be a hint of how dependency works, with ancestors nested in the subfolders of the children classes or something similar? Anyhow, thanks a lot for having answered so promptly! :) Mac. > > While I am working my way up to a more pythonic and cleaner style in > > the code, one thing that I have very confused ideas about is how I > > should organise my code, in terms of classes and files. > > I don't think there is any definitive answer. > > - Put reusable components into modules. > > - Don't necessarily create a module per class, but rather gather > related classes into a single module. > > - Build modules "bottom up" so that depenedencies tend to > go one way, with higher level modules importing lower level ones. > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to know if process is running?
I am not an expert, but if I got you correctly, what you want to achieve is a "singleton": http://en.wikipedia.org/wiki/Singleton_pattern if you watch at the sample implementation, there is a Python example too. Mac. On Tue, 2009-07-28 at 10:45 -0500, shawn bright wrote: > Hey all, > > I have an app that runs in a GUI written in pygtk. It spawns several > threads, and runs all the time. > It is mission critical that we can never have two instances of this > running at once. > > So, my question is, how can i write something that will know if there > is an instance of that something already running? > > I am doing this in python 2.5 on Ubuntu, if that matters ( which i > suspect it does ). > > thanks, > shawn > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Two problems related to dispathing.
Hello, I'm working on an application in which I need the main loop to call the same method on a number of objects. I came up with this solution that seem to work, but I was wondering if there is a better / more pythonic solution to the problem. def invokeAll(method, data): """This function is a dispatcher: it invokes all the content types of the application calling 'contenttype.method(data)'""" return [getattr(content, method)(data) for content in contents] I am also unsatisfied by how I generate the content list I use in the above function. In fact, as I have the need to access the object both individually and with the dispatcher, I am doing something like this every time I instantiate a new object: mycontent = ContentA() contents.append(mycontent) ...but although I "feel" this is silly, I can't imagine how to get it better (i.e. a single call that will make available the object with his unique name and append it to the list of contents. Thank you in advance for your input, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Two problems related to dispathing.
On Tue, 2009-07-28 at 19:03 +0100, Alan Gauld wrote: > There is no simpler solution without changing the class. > If you can do that you could pass the container to the constructor > and get the class to add itself to the container Kent, Alan... thank you very much, indeed I finally adopted the solution that both of you suggested, and I am now an happy man! :) Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Troubles with the mailing list.
Hi all, having seen a few people in the past days sending "trial messages" on the list I figured it out that I must not be the only one to experience problems with it. I even set up the "notification" feature that sends you an acknowledgement message when your mail is received from the server, but as a matter of facts, I did not even got that back for my previous message. I was just wondering if the list-owners are aware of the problem or not, and if anything can be done to fix it. Mac. PS: I also notice that some messages (quoted in replies) are not reaching my mbox or are reaching it after I got a reply to them. This could be a problem on my side though. Anybody experiencing similar issues? (I am using gmail, btw). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Web framework: looking for python-tutor's angle.
A couple of months ago I took the time to read a few articles on python web application frameworks and I got the impression that the two most mature and active projects are Zope and Django. Zope vs. Django hits 879.000 pages on google but much of the debate - or at least this is my impression - falls into the class "vi vs. emacs" or "gtk vs. qt" with many people singling out a single characteristics that for them is THE characteristic making one framework better than the other. This [1] graph seems to corroborate my final impression (i.e. that django is the way to go). Yet, I would be very interested in hearing what the members of this list think, as I particularly enjoy the "learner centered" approach that most of the people seems to have here. I believe my needs are quite ordinary: my customers are typically small businesses needing to process their data on a single server, sometime exposing part of the application as front-end to the customers (hence easy and flexible theming is important). I would definitively be happy to sacrifice some functionality in exchange for a leaner and cleaner design (i.e. more modular, elegant and intuitive), though. Thank you in advance for your time, Mac. [1] http://www.google.com/trends?q=python+zope%2C+python+django ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] rationale for nested classes?
On Fri, 2009-08-14 at 11:26 -0400, Serdar Tumgoren wrote: > Hi everyone, > > I was wondering if there's anyone who can offer a use case/rationale > for nested class? ... > Are there specific situations when nested classes come in handy > (perhaps for grouping conceptually related classes that don't share > attributes?). Disclaimer: I am not a python-ninja and do not have much python code under my belt, but since I thought to what I am about to write when I first read your question, and nobody else gave feedback in this direction, I though to share my idea, if not for anything else, at least to be told on why this might be a non pythonic one :) . I would use a nested class to create a particular data structure which represent a "sub-unit" of the mother class. For example if I had a class representing a table (with methods like add, delete, sort, etc...) I might wish to create a subclass that represent a record and use instantiation of that sub-class as my main way to handle data. In this way I could enforce behaviours like "not null" or "default" from within the datastructure itself (for example in the __init__ method) rather than enforcing a logic from outside (i.e. the "mother class"). I believe classes/objects are also the most elegant way to implement singletons, so maybe if you need a singleton for each object generated with the "mother class", maybe that is also an occasion in which a subclass comes handy. Finally, I somewhere read that embedded declarations are much faster than external ones in being referenced. So, if performance is an issue, maybe embedding one class within another one might bring you some benefit rather than having an object instantiated from the first class having to reference a class which is external to its generating one. [Hope that is understandable... English is not my first language... :)] Anyhow let me reiterate my disclaimer: I am not a python guru, so I would be very happy if any of the tutors would comment on what above, even if it is for disagree with it! :) Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] rationale for nested classes?
On Mon, 2009-08-17 at 13:33 -0400, Kent Johnson wrote: > On Mon, Aug 17, 2009 at 1:12 PM, Mac Ryan wrote: > > > Finally, I somewhere read that embedded declarations are much faster > > than external ones in being referenced. So, if performance is an issue, > > maybe embedding one class within another one might bring you some > > benefit rather than having an object instantiated from the first class > > having to reference a class which is external to its generating one. > > [Hope that is understandable... English is not my first language... :)] > > *Local* variables are faster than variables that must be looked up. > Nested classes would not qualify for this. I could not find the article I was referring to, so I ran a test myself, and - surprisingly - I found out the exact contrary of what I read. Nesting the class lower the performance of nearly 10%. FLAT: [4.0505850315093994, 4.0618939399719238, 4.0537300109863281] import timeit class Printer(object): def __init__(self): a = 3 ** 3 class Embedder(object): def __init__(self): for i in range(1): a = Printer() if __name__ == '__main__': timer = timeit.Timer("new = triedout.Embedder()", "import triedout") print timer.repeat(3, 1000) NESTED: [4.3873238563537598, 4.3799960613250732, 4.3729050159454346] import timeit class Embedder(object): class Printer(object): def __init__(self): a = 3 ** 3 def __init__(self): for i in range(1): a = self.Printer() if __name__ == '__main__': timer = timeit.Timer("new = triedout.Embedder()", "import triedout") print timer.repeat(3, 1000) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] rationale for nested classes?
On Mon, 2009-08-17 at 20:27 +0100, Alan Gauld wrote: > > way I could enforce behaviours like "not null" or "default" from within > > the datastructure itself (for example in the __init__ method) rather > > than enforcing a logic from outside (i.e. the "mother class"). > > But those features are features of the record not of the table. > A table is simply a collection of records. Most of the functionality > should be in the record, the table should only need to insert,delete, > search, sort etc. And those methods should be written to use > polymorphism to be record independent I suppose one of us is missing the point of the other one, as it looks to me that we are saying the same. :) I would indeed enforce those checks and defaults in the child class (i.e. nested) so that the mother class can have "generic methods" that would work with various records. Indeed - if I truly wished to use nested classes - I would probably define certain module-wide "generic" classes for both "tables" and "records" and then I would subclass them in hierarchic form, so that the class TableA(Table) has a nested class RecordA(Record). I would think of that as a legitimate design with strong encapsulation. Again though... I am not advocating for this method as "the best one", I am just try to imagine a "rationale for nested classes" as per request of the OP. > > I believe classes/objects are also the most elegant way to implement > > singletons, so maybe if you need a singleton for each object generated > > with the "mother class", maybe that is also an occasion in which a > > subclass comes handy. > > I have no idea what you mean by that bit. Classes can be used for > singletons but I don;t see where nested classes come into it. Mmmm... giving a second thought to it, what I had in mind can be achieved with a single class. So apologies, disregard this bit! :) > > would be very happy if any of the tutors would comment on what above, > > even if it is for disagree with it! :) > > Be very happy! :-) > More seriously, I suspect from your comments that you too are > getting confused about the difference between inheritance and nesting. > nesting is about hiding the class name and definition. Inheritance is > about subclassing. They are very different concepts. Nesting tends > to make subclassing more difficult (albeit in Python only trivially so) Well, thank you for the feedback indeed. I am one of those people who get their mind clear only when they interact with others. As for the confusion between nesting and inheritance... no, I think I have that one pretty well under my belt. :) Thank you again, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Packaging for distribution
On Thu, 2009-08-20 at 11:26 -0500, Wayne wrote: > Hi, > > > I have a program written in python + pygtk and I'm trying to figure > out what would be the best way to distribute my program. I've googled > all over and I find lots of build scripts, the py2exe utility... > > > It just seems that they're either extremely complicated for what I > need (which means I could write my own installer in the time it would > take me to learn these), or produce massive files (in the case of > py2exe). > > > Does anyone know of any guides/resources, or are these my best bet? I am a fellow learner here, and will follow this thread with very much interest. Just in case you don't know this already: I am considering bytecode instead of executable with PyInstaller (http://www.pyinstaller.org/). I have not tinkered with it yet, though, so I do not have "first hand impressions" to share. From a review of the features: Main Pro's: - Compact resulting files. - Cross-platform. - Flexible licensing scheme. Main Con: - Support for 2.6 is not yet fully functional. Best luck! Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
On Sun, 2009-08-23 at 15:06 -0700, kreglet wrote: > Hello, > > The problem that I am having is writing an algorithm for finding all the > possible words from a given word. For example: python > > from "python" you can make the words pot, top, hop, not etc. There are few > examples for making anagrams for a word, but only the whole word. I have > tried unsuccessfully to modify some of these to suit my purpose. Also on the > web there are numerous sites where you can type in a word and it will give > you a list of all the words that could be made from it. How would I go about > this in python? > > thanx, > kreglet Of course doing things by yourself is more exciting and fun (and above all you have the pleasure to learn something new), but if you finally should decide to invoke an external utility (e.g.: for performance issues), then you might be interested in using "an": it's very fast and in the repositories of most linux distro. It has plenty of options. Example usage: an -m4 -w python [search only for single words in the dictionary with a minimum length of 4 letters] returns: hypo phony pony python tony typo Good luck with your project, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Pexpect latest version.
Hello everybody, this is more a request of info than of help. I want to play around with pexpect a bit, but I am confused on what is the latest stable version. On SF (linked from the site of the pexpect developer) http://pexpect.sourceforge.net/pexpect.html it seems the latest version (2.3), but I was able to download the 2.4 from here: http://pypi.python.org/pypi/pexpect/ which is just over one year old. On the other hand the version included in the repos of my linux distro is 2.3.1. So my questions: 1. Does anybody know if both version are compatible with python 2.6? 2. Does anybody know if 2.4 is a stable (secret) version? Of course if you have experience with pexpect and feel compelled to give some preliminary advice (like known limitations or quirks that take hours to understand, or "don't use it because is broken" kind of remarks) I will be glad to hear those as well! :) Many thanks for your time, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Declaration order of classes... why it is important?
Hello everybody, I am using "storm" (https://storm.canonical.com/) to manage my database. In storm, relationships between tables (each table is represented by a class) are expressed like this (line #4): 1 >>> class Employee(Person): 2 ... __storm_table__ = "employee" 3 ... company_id = Int() 4 ... company = Reference(company_id, Company.id) where Company is another class. Now, what I noticed is that Company must be declared as a class before Employee, or python will throw an exception (Company is not defined). I would be interested in understanding why this is so designed. I expected that the exception would not be thrown at all, as I imagined that the interpreter simply kept track of where classes were declared and would try to evaluate the code only once an actual object would be instantiated (at that point the interpreter would know where to look for each class code). BTW, the behaviour I am describing is exactly what happens with function declaration: the following code evaluates as expected, indeed. def fone(): ftwo() def ftwo(): print "hello" fone() I would also be interested in knowing if there is a way around this or if I simply have to live with it. It is not that this impede to achieve anything, but in reading code, I normally prefer to have the big picture first [This is a house, as you see is composed of walls, roof, basement. A wall can have...] while this behaviour obliges me to write the code the other way around ["This is a brick, if you put together bricks you get a wall, if you put together walls you get..."] Thanks in advance, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote: > So define a classmethod to finish the job, and invoke it later > > class Employee(object): > @classmethod > def finish(cls): > cls.__storm_table__ = "employee" > cls.company_id = [] > cls.company = Company.id #where Company is a forward > reference > del cls.finish #remove this method so it won't be called a > second time > > class Company: > id = 42 > > Employee.finish() #This finishes initializing the class > > > help(Employee) > print Employee.company_id First things first, thank you Wayne, Kent and Dave for your extensive and complementary explanations. As many things in python, what it seemed obscure at first now - with your help - seems perfectly obvious. Second thing: the example that Dave gave me and that I left quoted above makes use of decorators, but this is something that I still do not understand. I believe I got a grasp of the concept of metaclasses, to which the concept of decorator seems to be related, but the official documentation is a a bit obscure for me. I don't want to steal your time asking for an explanation that probably is already somewhere out there, but my google searches did not return anything useful (I assume I am using the wrong keywords here), so if you have a good pointer for me, I would be very grateful. :) Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: > Now there are a couple of decorators that are in the standard library > that everyone should know about:classmethod() and staticmethod(). > They wrap a method in a new one (which ends up having the same name), > such that the first argument is either eaten (staticmethod), or changed > to a class (classmethod). > > Hope that was sufficient detail. > > DaveA Thank you all for your answer, I read the link posted by Kent end the explanations given by others, and now almost all the pieces of the puzzle are falling to their place. The (last?) thing still escaping my understanding is the difference between classmethod() and staticmethod(). I understand that both of them are to make sure a method will be associated with the class rather than with an instance of it (a bit like variables declared in a class but outside a method), so I assume I should use them like: class myClass(object): @staticmethod / @classmethod def method_of_class(self): pass def method_of_instances(self): pass I am not sure I understood the difference between staticmethod end classmethod, though, even if I can guess it has to do with subclassing, (given classmethod go fish for the class name)... am I on the right track? Any hint (or full-fledged explanation!)? :) [The official documentation is a bit obscure for me as it refers to C# and Java, languages that I do not know.] Also, what is the advantage of using a method at class level rather than using it at object instance (I can imagine you can save some memory by not duplicating X times the same code, maybe... but what kind of designs require/call for use of statc/classmethods?) Thank you in advance for your help, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Fri, 2009-08-28 at 08:55 -0400, Dave Angel wrote: > Mac Ryan wrote: > > On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: > > > > > >> Now there are a couple of decorators that are in the standard library > >> that everyone should know about:classmethod() and staticmethod(). > >> They wrap a method in a new one (which ends up having the same name), > >> such that the first argument is either eaten (staticmethod), or changed > >> to a class (classmethod). > >> > >> Hope that was sufficient detail. > >> > >> DaveA > >> > > > > Thank you all for your answer, I read the link posted by Kent end the > > explanations given by others, and now almost all the pieces of the > > puzzle are falling to their place. > > > > The (last?) thing still escaping my understanding is the difference > > between classmethod() and staticmethod(). I understand that both of them > > are to make sure a method will be associated with the class rather than > > with an instance of it (a bit like variables declared in a class but > > outside a method), so I assume I should use them like: > > > > class myClass(object): > > > > @staticmethod / @classmethod > > def method_of_class(self): > > pass > > > > def method_of_instances(self): > > pass > > > > I am not sure I understood the difference between staticmethod end > > classmethod, though, even if I can guess it has to do with subclassing, > > (given classmethod go fish for the class name)... am I on the right > > track? Any hint (or full-fledged explanation!)? :) > > > > [The official documentation is a bit obscure for me as it refers to C# > > and Java, languages that I do not know.] > > > > Also, what is the advantage of using a method at class level rather than > > using it at object instance (I can imagine you can save some memory by > > not duplicating X times the same code, maybe... but what kind of designs > > require/call for use of statc/classmethods?) > > > > Thank you in advance for your help, > > Mac. > > > > > > > I thought someone (me) had already posted examples. The method itself > looks different in the three cases: > > class MyClass(object): > > def my_method1(self, arg): > ... do something with this particular object > > @classmethod > def my_class_method(cls, arg) > do something that may requires use of class, but > that doesn't need to know the particular object > > @staticmethod >def my_static_method(arg): > do something which isn't affected at all by what > class it's in > > self and cls parameters are named that merely by convention. Unlike the > "this" of C++, C#, and Java, these names have no specific meaning to the > compiler. But convention is a very good thing, especially in this case. > > So the first difference between static and class is that the method > signature must be different. There's an extra parameter on the latter > that must be included. The second difference is that a classmethod may > call other methods of the same class, and gets the appropriate methods > even if the class was subclassed. > > The hint to play with is that any of these 3 may be called with an > object (obj.my_class_method()), and the last two may be called with a > classname. > > DaveA Thank you Dave, very helpful as ever. I made a few tests and experiments to understand better, and I feel I am understanding how it works. Although the mechanic of this is increasingly clear, the logic behind is still a bit obscure: here comes a silly test on which results I have questions about == class A(object): variable = 0 @classmethod def cm(cls): cls.variable += 3 class B(A): pass class C(B): pass a = A() b = B() c = C() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' b.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' c.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.variable = 7 A.variable = 4 print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' B.variable = 'x' print A.variable, a.variable print B.variable, b.variable print C.va
Re: [Tutor] Declaration order of classes... why it is important?
On Fri, 2009-08-28 at 12:24 -0400, Dave Angel wrote: > > Thank you Dave, very helpful as ever. I made a few tests and experiments > > to understand better, and I feel I am understanding how it works. > > Although the mechanic of this is increasingly clear, the logic behind is > > still a bit obscure: here comes a silly test on which results I have > > questions about > > > > == > > > > class A(object): > > variable = 0 > > @classmethod > > def cm(cls): > > cls.variable += 3 > > > > class B(A): > > pass > > > > class C(B): > > pass > > > > a = A() > > b = B() > > c = C() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > a.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > b.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > c.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > a.variable = 7 > > A.variable = 4 > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > B.variable = 'x' > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > > > == > > > > Now, the output of this test is as follows (I manually added the numbers > > on the right for reference in the remaining of the post): > > > > 0 0 # 1 > > 0 0 > > 0 0 > > --- > > 3 3 # 2 > > 3 3 > > 3 3 > > --- > > 3 3 # 3 > > 6 6 > > 6 6 > > --- > > 3 3 # 4 > > 6 6 > > 9 9 > > --- > > 4 7 # 5 > > 6 6 > > 9 9 > > --- > > 4 7 # 6 > > x x > > 9 9 > > > > #1 is plain obvious. > > > > #2 came as a bit of surprise: "Ah-ah!... so the class variable is the > > same for all the hierarchy of classes! I would have guessed each class > > had its own variable..." > > > > #3 and #4 are bigger surprises: "Uh? let me understand better, so... it > > must be like branches... as soon as I say that B.variable is different > > than its ancestors, all the descendants of B get updated... Yet, it's > > strange: this very thread on the mailing list has started with me asking > > about the order of declaration for classes, and I have been told that > > class variables are processed as soon as the interpreter hits the class > > definition... so I would have expected that C.variable would have been > > initialised already and would not dynamically change when B.variable > > does..." > > > > #5 confused me: it seems that a.variable can refer to both the class > > variable or a newly created object property... that sounds like a > > never-ending source of bugs to me: it is me who has then to remember if > > a given syntax refers to a class variable or to an object method? > > > > #6 really make no sense to me: it seems that the class variable of C has > > not been changed this time (as it did in #3)... > > > > The points above confuse me even more about the "design purposes" of > > classmethods and staticmethods... > > > > Any help/feedback, very much appreciated. > > > > mac. > > > > > > > Great questions. I love a person who is organized as you are. And as > willing to learn. > > #3 and #4 - First let me point out that these are not class variables, > but class attributes. It's unfortunate that you called the attributes > with the label 'variable'. I frequently make the same mistake (call it > sloppy mistake), but it might matter somewhere in the following > discussion. A class variable is simply a "variable" which references > the class. Think of it as an alias for the class. Just like a list > variable is a variable which references a list. If you do: > newclass = A > > then you can use newclass in exactly the same way as A. a = > newclass(), print newclass.variable, etc. > > A class attribute, on the other hand, is what other languages would call > a field of the class. And it definitely does get initialized when the > class is executed. That's important in the earlier discussion because > the *right-hand-side* has to be valid at that time, which is why you had > the forward referencing problem. So in the following code: > > n = 12 > class A(object): > attr = n > > n = 42 > > > the attribute A.attr is a reference to 12, not 42. The confusion in > this #3 and #4 case is that when some later expression tries to use a > particular class attribute there are some rules for lookup. I don't > know the correct terminology, but I think of this as the "." operator. > When I say C.variable, the first search is in the classes dictionary. > If it's not found there, then it searches in the parent class' > dictionary, and so on. The attribute is not copied, there's just a > search order when it's accessed. > > #5 - It'
Re: [Tutor] Declaration order of classes... why it is important?
On Fri, 2009-08-28 at 18:03 +0100, Alan Gauld wrote: > "Mac Ryan" wrote > > > I am not sure I understood the difference between staticmethod end > > classmethod, though, even if I can guess it has to do with subclassing, > > I think it is mainly historical. staticmethod came first (I think) and > classmethod > was an improvement a couple of versions later. I think classmethod is the > preferred choice nowadays. > > > Also, what is the advantage of using a method at class level rather than > > using it at object instance > > There are two common cases: > > 1) You want to do something at the class level rather than instance > level - such as find all instances, or keep a count of all instances. > Or you may have a method or variable that affects all instances > simultaneously - perhaps activates or disables all network connections > say. > > 2) You want somethig that can be done without creating an instance, > or at least does not depend on whether any instances exist yet. This > is very common in Java which doesn't support standalone functions > but is not needed so much in Python because a module function is > usually a better option. > > You can also use it to provide meta-class programming features > and other tricks, but frankly thats usually being too clever for your > own good! :-) > > HTH, Thank you Alan, that totally answer my question about classmethods. :) What is still unclear to me, is what the staticmethods are for, though: since the reference to the object instance or to the class object are stripped away from the call, I wonder why not to use a module function instead. The only difference I can think of between the two (static method and module function) is that the namespaces they "live in" are different (mymodule.function vs. mymodule.myclass.function)... but I suspect there must be a better and more important design reason to have them implemented in the core... Many thanks in advance for your help, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Sat, 2009-08-29 at 11:44 +, ALAN GAULD wrote: > First recall that xsstatic methods were historically the first attempt at > giving Python class methods. (They were called staticmethods because > C++ and Java define their class methods using the label 'static' ) > ... > > The only difference I can think of between the two (static method and > > module function) is that the namespaces they "live in" are different > > And that is significant. > > Alan G Ok, now I am an happy man. :) Thank you for your time! Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert binary files back to text files?
On Sat, 2009-08-29 at 18:42 +0530, prasad rao wrote: > >On 8/29/09, Geneviève DIAGORN wrote: > >Bonjour, > >Je suis absente jusqu'au 02/09 inclus. > >En cas d'urgence Soprane, contacter notre adresse générique > >projet.sopr...@teamlog.com. > >Cordialement. > > >Geneviève > > I dont know your language.Please communicate in English. The message just says the person is out of office until the second of september. Unluckily her company (which is an IT company!!!) seems to be unable to properly configure an autoresponder... Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Initialize Class Variables by Dictionary ...
On Sat, 2009-08-29 at 16:31 -0400, Damon Timm wrote: > Hi again - thanks for your help with my question early today (and last > night). Tried searching google for this next question but can't get > an answer ... here is what I would like to do (but it is not working) > ... > > >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'} > >>> class Test(): > ... def __init__(self): > ... for key in dict: > ... self.key = dict[key] > ... > >>> t = Test() > >>> t.test1 > Traceback (most recent call last): > File "", line 1, in > AttributeError: Test instance has no attribute 'test1' > >>> t.key > 'value3' > > Can I do what I am dreaming of ? Yes you can, but not that way. Here is how I did on my console: >>> class A(object): ... pass ... >>> dir(A) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>> setattr(A, 'test1', 'mytest') >>> dir(A) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'test1'] >>> A.test1 'mytest' So, the key here is to use the setattr() builtin function. However keep in mind that I am a python beginner, so you would probably like to hear from some real tutors before implementing this solution all over your code... Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please delete my mail address from that mail list. Thanks!
On Tue, 2009-09-01 at 04:27 +0200, Luke Paireepinart wrote: > there are directions on how to remove yourself from the list at the > bottom of every message that the list sends out. > ___ > click. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor May I suggest, to slightly tweak the signature of the ML with something like: --- Tutor mailing list - tutor@python.org Configuration options (including unsubscribing): http://mail.python.org/mailman/listinfo/tutor --- so that the less tech-savvy among the subscribers get a better hint on how to manage by themselves? Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to read and transmit/send only section of the image (sub-image)
On Fri, 2009-09-04 at 00:01 +0200, Jojo Mwebaze wrote: > thanks guys, > > > Currently i am using pyfits, a bit slow cause loads the file in > memory, creates a subimage and then saves the file then transmits > the file over the network! My idea is, if there is a way of creating > a file pointer to the location on disk, where the subimage lies, > reading a specific size, and sending only the data read (like wayne > had suggested) > > > Do you think this possible? > > > Johnson I had no chance to look at the specific format of your image files, but unless it is an uncompressed raster I would guess what you want to do is rather difficult. Chances are indeed that the data in the image files are compressed, and this means that part of the information needed to properly render your sub-image lies in another part of the image that you are not interested in. Just think of compressed videos, a lot of codecs use the idea of "key frames": if for any reason you lose a key-frame, for a few seconds after that missing frame you won't see a proper video, but most probably a greenish moving blob, as what the video player is actually trying to do is modifying parts of the key-frame that is not there. Another problem is that the ratio raw data / compressed data is not constant throughout the entire file: I would guess that a portion of an image that is simply black deep space will be compressed in a few bytes, while a portion of the image of equal extension but with a galaxy in it will be compressed into a larger chunk of bytes, so - unless you have an index - it will be *very* hard for you to guess where your "sub-image" lies in your master file. Again: as I did not check out your file format specifically, you should check out by yourself if what above applies to you or not. It might well be that the format you are using was specifically designed to allow operations like the one you describe, and that the metainformation needed for you to access you sub-image are in the header of the master image. I just wanted to give you some input on you question "do you think this is possible?". :) Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help deciding between python and ruby
On Fri, 2009-09-04 at 06:18 -0700, dan06 wrote: > I'd like to learn a programming language - and I need help deciding between > python and ruby. I'm interesting in learning what are the difference, both > objective and subjective, between the two languages. I know this is a python > mailing list, so knowledge/experience with ruby may be limited - in which > case I'd still be interested in learning why members of this mailing list > chose python over (or in addition to) any other programming language. I look > forward to the feedback/insight. IMO "python vs. ruby", "vi vs. emacs", "gtk vs qt" and company are all kind of comparisons where the ultimate "right" outcome is invariably a matter of taste. Both languages are powerful, mature and flexible enough to be used as an "all round" programming language. The only "objective" factor that IMO is truly important in the choice is if you are planning to develop for a specific platform that is biased towards one of the two. For example, I am using a linux distro (ubuntu) which is strongly python-oriented, and picking python instead of ruby makes my development cycle easier/smoother (all most commonly needed libs are in the repos, packages are up-to-date, most of the documentation has been ported to the standard developer's help application, etc...). As for "subjective" reasons, I can only share those that played a role *for me*: 1. Python community is fun-oriented: having fun while programming and while learning is part of the established python-culture. I tend to be an happy person, and I simply enjoy reading a book or following a tutorial that cracks a joke here and there and that does not take itself too seriously. 2. Whitespace is significant: this in turns makes code look very much alike on a page regardless of whom wrote it. Code is clean... I tend to be a clean person too! ;) 3. Python is heavily adopted by companies with a long-standing tradition of openness (in the sense of free-as-in-freedom-software). I could name here at least two: Canonical ltd. (mother of ubuntu) and Google inc. (you might have heard of it already ;). 4. I love the "monthy python". 5. Support in python communities is awesome, again I believe this has something to do with the "python-culture". Take this list as an example: it seems that people here made an oath to go the extra mile in helping others, and supporting them in their own learning. 6. Python comes with "batteries included" (i.e. the core distribution has a lot of functionalities that in other languages would require you to import external resources). While this makes it slightly bigger than more essential languages, I still feel the trade-off in terms of productivity and fun are worth the extra weight). That's why *I* chose python over ruby. As Luke already said, I would be happy too to know your reasoning if you would finally choose to go for ruby! Best luck, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Question
On Thu, 25 Nov 2010 00:58:23 + Adam Bark wrote: > Ah yes always avoid giving your modules names that appear in the > standard library. It goes wrong, sometimes in unexpected ways. I was wondering... apart from checking each name individually, is there any easy-peasy way to get a list of names used in the standard library (I am thinking to something like "dir()"? Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Question
On Thu, 25 Nov 2010 11:09:10 +0100 Timo wrote: > > I was wondering... apart from checking each name individually, is > > there any easy-peasy way to get a list of names used in the > > standard library (I am thinking to something like "dir()"? > This is the webpage I always use for searching an appropriate module: > http://docs.python.org/modindex.html I was more thinking to some introspective capacity of python itself rather than a web page... yet, thank you for the link that I did not know beforehand! :) Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Question
On Fri, 26 Nov 2010 18:33:07 +0100 Piotr Kamiński wrote: > You can get the list of Python's standard modules by typing help() > and then you will see something similar to: Thanks a lot! This is what I was after! Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Exercise
On Sat, 27 Nov 2010 22:00:03 +0800 Kok Cheng Tan wrote: > I created this website for practising python online: > http://www.pyschools.com. Hope to gather feedback from people here > who are interesting in teaching and learning python. Here you go with the first suggestion: remove the need to log in! (Haven't really watched at the site content, given that I - like 99% of the Internet users - wouldn't bother to login just to roam around a site). Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Conceptual Question About Use of Python for Employee Training Program
On Sat, 25 Jun 2011 06:18:14 -0700 (PDT) Adam Carr wrote: > Good Morning: > > I am very new to Python but I am enjoying the learning process. I > have a question about the application of Python to a problem at the > industrial business where I work. My two main questions are: > > 1. Can Python be used to achieve the goals of the possible project? > 2. Where are the best places to look (books, blogs, websites, etc.) > for programming examples or modules that would help me begin to > assemble and test some code? > > We currently have a Windows-PC based safety training program that was > put together in MS Access around 2001 > Thanks in advance for taking the time to read my long note. I > appreciate any help or direction that can be offered. Hi Adam, from the way you describe your problem, to me the obvious answer would be "web application". This way you will be able to: 1. Make sure all employees will use the latest up-to-date training material and software version. 2. Have a central DB able to track employees' activity (this opens up the possibility for extra functionalities like sending a "gentle reminder e-mail" to those who are not taking tests frequently enough, statistics on what topics employees struggle most with, etc...) 3. Be platform independent. 5. Save time on developing the GUI (which - done properly - is a very time consuming part of desktop projects). That said, python is a great tool for web apps too. I personally looked a bit into Django (www.djangoproject.com), which is one of the python web frameworks and I was impressed by the speed you can prototype a fully working application. As for presenting the training material, for iteration #1 I would simply make them available as a download link. But in following iteration of the project I would also integrate them with the web (so as to make the entire application truly portable. I once used S5 for a project. Here you can see a presentation of it that is - coherentely - done with the standard presented: http://meyerweb.com/eric/tools/s5/s5-intro.html#slide1 However an alternative I did not experiment with is XOXO, which I read has python code examples available (see http://microformats.org/wiki/xoxo-sample-code-python) HTH, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Conceptual Question About Use of Python for Employee Training Program
Just thought to google for "S5 python", and google came out with a lot of interesting links! :o /mac > Good Morning: > > I am very new to Python but I am enjoying the learning process. I > have a question about the application of Python to a problem at the > industrial business where I work. My two main questions are: > > 1. Can Python be used to achieve the goals of the possible project? > 2. Where are the best places to look (books, blogs, websites, etc.) > for programming examples or modules that would help me begin to > assemble and test some code? > > We currently have a Windows-PC based safety training program that was > put together in MS Access around 2001. Access has evolved through > several versions since then, as has the Windows OS, and the original > author of the database has left the company. Originally designed to > be deployed on an employee's desktop, the database is now restricted > to two older PCs in the facility that run a version of Access > compatible with the original. In short, the program is quickly > becoming obsolete. > > The safety training program is a monthly exercise for all thirty nine > employees at our location. The training is mandated by OSHA, and the > subject matter is chosen based on the relevance to our processes. The > program consists of the following general steps. > > 1. The employee is prompted to enter his or her employee identity > number. > > 2. A confirmation is generated showing the employee name and other > minor details, accessed from a simple list, to be sure the identity > number and the person are correctly matched. This requires employee > acknowledgment. > > 3. The employee freely selects a training subject from a list. > > 4. Once a subject is selected, a PowerPoint (or could be the > OpenOffice Presentation) is launched. The training information is in > the presentation. The employee can navigate forward or backward > through the presentation, or they can exit. > > 5. Once the presentation is complete, or the employee has started and > used ESC to exit from the presentation, they are prompted to take a > quiz or exit the training program. > > 6. The quiz is a simple true-false ten question process based on the > material in the training presentation. > > 7. The employee clicks on their answers to questions, the quiz is > completed and scored. The employee must get at least eight of the ten > questions correct to pass the topic. > > > 8. Right now the Access version of the program prints the quiz, the > employee's answers and the correct answers to the quiz, and the hard > copy is signed and left with their supervisor. The printer is the > default location set for the machine on which the training and quiz > are completed. I think that the only reason the quizzes are printed > is because no topic and quiz verification process was written into > the program. In other words, an employee can take the time to review > a topic, take and pass the associated quiz but if the printed copy is > lost there is no way to verify that the employee completed anything. > > > I would like to see a program that can be deployed as originally > intended, on individual PCs, that can be more easily maintained and > modified than the behemoth Access program we now have. We are running > a Windows network with most production floor PCs using the latest > version of XP and most individual desktops and laptops using Windows > 7. I have the blessing of our network gods to pursue an open source > solution because the options for this kind of program, which is > tailored to individual locations, are few. The best approach the > network folks suggested was a Lotus Notes database, which would work > great I'm sure but the development cost is very, very high and each > of the company's many manufacturing locations would require a > slightly different version of the database. > > Thanks in advance for taking the time to read my long note. I > appreciate any help or direction that can be offered. > > Adam ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Standard way to create debian packages for python programs?
Although it's years I program with python, I never distributed my software with packages (I never created *any* packages in my life, indeed). Out there there is ton of information on how to do this, but after a day of scouring the Internet I still did not wrap my mind around it. The problem for me is that "there is more than a way to skin a cat", and all the tutorials/manuals that cover a bit of the process seem to make certain assumptions which are different from other tutorials, sot that is not self-evident how I should merge the info from two sources together. For example: when I find a manual on how to create a binary package, it is assumed there are makefile for C code, when I find a page on how to use distutils, it is assumed I want to "package" a module and not a stand-alone program, etc... So I am turning to the community to ask for advice/guidance. So far I seem to have understood the following (please correct me if I am wrong): a) I need to create a "binary" .deb package. Such package will be platform independend (32 vs 64 bit) as all python programs are such. b) To create a "binary" package I need first to create a source package. c) To create the source package I can use either CDBS or debhelper. Debhelper is the recommended way for beginners. d) The core of creating a source package is populating the DEBIAN directory in the source directory with a number of files clarifying where files need to be copied, what copyright and licensing scheme they are subject to, what dependencies they have, etc... e) Step d) can be largely automated the 'dh_make' command IF the python source also comes with a distutils' setup.py script. Now my questions: 1. Is my understanding of the process correct? Is there anything I am missing, or anything that I got wrong? 2. Step e) is really the more confusing to me: specifically the two points that remains most obscure to me are: I. How do I write a script that install a stand-alone programe? II. What are the specificities for DEB packages? The official documentation only seems to deal with RPM and Windows stuff... 3. Is there any "reasonable sized" source of information that you would recommend me to read [by "reasonable sized" I mean something specific to python and concise, rather that the complete debian policy on packaging]. 4. Any word of wisdom / additional info you would like to share? BTW: This is are the best source of information that I could find myself so far: - Ubuntu's python packaging guide (clearly explains steps a-b-c): https://wiki.ubuntu.com/PackagingGuide/Python#The_debhelper_way - Creating a .deb package from a python setup.py (it _shows_ the steps but doesn't _explain_ them enough for me to follow along): http://ghantoos.org/2008/10/19/creating-a-deb-package-from-a-python-setuppy/ - ShowMeDo video on "creating a .deb package out of a python program" (it doesn't seem up-to-date and - if I got it right - will produce packages for personal use, without dependencies and without key data for distribution with ubuntu/debian): http://showmedo.com/videotutorials/series?name=linuxJensMakingDebSeries Thanks in advance for your help and support! /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Standard way to create debian packages for python programs?
On Thu, 18 Aug 2011 22:43:09 +1000 Steven D'Aprano wrote: > Mac Ryan wrote: > > Although it's years I program with python, I never distributed my > > software with packages (I never created *any* packages in my life, > > indeed). > > This is a mailing list for learning the programming Python, not on > how to built Debian packages. > > You will probably get better answers if you ask this question on a > Debian packaging forum. Steven, I appreciate the feedback, yet it feels like you did not read my question through: apart a general feedback about the packaging process [which I felt important to explain in case I got it totally wrong and was asking something that did not make sense at all] the other to points are specific to python. In particular, `distutils` is part of the standard python distribution and it is in no way specific to Debian, so I don't feel this is the wrong place to ask, although it's totally ok if tutors feel they aren't competent enough on the subject to give proper feedback. :) I will surely cross-post on some debian-specific ML or forum, but I don't think I will have better luck in getting feedback on distutils there than on a python-specific ML like this one. I will let you know if I will be proved wrong, though! :) Best, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Standard way to create debian packages for python programs?
On Thu, 18 Aug 2011 13:01:08 -0400 Brett Ritter wrote: > On Thu, Aug 18, 2011 at 11:39 AM, Mac Ryan > wrote: > > In particular, `distutils` is part of the standard python > > distribution and it is in no way specific to Debian, so I don't feel > > this is the wrong place to ask, although it's totally ok if tutors > > feel they aren't competent enough on the subject to give proper > > feedback. :) > > Are you looking for distutils advice, or .deb advice? They are pretty > different. > How are you expecting your users to install your package? Via > easy_install? Apt-get? Something else? Hi Brett, thanks for coming back to me. My goal is to have a .deb package installable with apt-get. What I am asking advice on is primarily the distutils script. The procedure on how to get to a .deb package is there just to give a context to my question and - hopefully - to have somebody tell me if I am 100% wrong and indeed a setup.py script is NOT part of the process. I'm going to reply to Ramit in a second and hopefully I will be able to further clarify there what I am asking. Thank you, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Standard way to create debian packages for python programs?
On Thu, 18 Aug 2011 12:48:19 -0400 "Prasad, Ramit" wrote: > To be honest, even after reading your original post twice (now > knowing you are actually asking a Python question) I am unsure what > Python question you are asking. Apologies, English is not my mother tongue, maybe I wasn't able to express myself clearly enough? > >2. Step e) is really the more confusing to me: specifically the two > > points that remains most obscure to me are: > > I. How do I write a script that install a stand-alone programe? > > I assume you can use Python and os.system or better yet subprocess > (worst case scenario Python calls the other utils). This is not > really a python specific question and you did not mention distutils > here. Either way I have no clue, sorry. You lost me, but I assume this is because you didn't get my question in the first place. My point "e" mentions the setup.py script that one must write for using distutils. This is what the question is about: how do I write a script that handle a full program with several modules, data files, etc? The official documentation seems not to provide an example for this. Since my posting this question here, I received a useful link for this from another source, that I'm still working through: http://wiki.python.org/moin/Distutils/Tutorial > > II. What are the specificities for DEB packages? The official > > documentation only seems to deal with RPM and Windows stuff... > > Not a Python question and no clue. It *IS* a python question as it refers to the distutils module. If you read the documentation (http://docs.python.org/distutils/builtdist.html) you will see that there are sections about windows exe installer and RPM packages, but none for DEB... how is so? Maybe distutils can't handle build distribution for this platform? Or maybe it is simply undocumented? > >3. Is there any "reasonable sized" source of information... > Not a Python question and no clue. > > >4. Any word of wisdom / additional info you would like to share? > Again, not really a Python question. In some 3 years I am member of this list I have seen thousands of messages containing pointers to external documentation and advice from this list users' personal experience... so they might not be technically about python code, but I'm positive they are not off-topic requests. > Something like: > http://showmedo.com/videotutorials/video?name=linuxJensMakingDeb OR > http://ghantoos.org/2008/10/19/creating-a-deb-package-from-a-python-setuppy/ > OR > http://ask.debian.net/questions/how-to-build-a-pure-python-debian-package Of the three links you provided, two were in my original question... The third link's answer only contains a link to another source from my original question... :( /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Standard way to create debian packages for python programs?
On Fri, 19 Aug 2011 00:08:30 +0100 Alan Gauld wrote: > I notice there is also a distutils SIG with a mailing list which > looks like they might help. A quick look at some mails suggests they > cover this kind of issue. > > FWIW I used the gmane web site to take a quick look... Thanks for both the suggestions. I just subscribed to the SIG group, although since my original call for help I already received a few inputs that helped me a lot. Best, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Standard way to create debian packages for python programs?
On Thu, 18 Aug 2011 14:55:19 -0400 "Prasad, Ramit" wrote: > Have you taken a look at: http://pypi.python.org/pypi/stdeb/0.5.1 Thank you for this. Actually I got the same advice also on my SO question here: http://stackoverflow.com/q/7110604/146792 at about the same time you answered me. Good source. [Also the link to the forum thread was good!] For the records: the other good piece of advice I received elsewhere was to look into `Distribute`, a collection of enhancements to `distutils` that indeed make the creation of setup.py easier for what I want to achieve. Here's a link to the docs for those interested: http://packages.python.org/distribute/setuptools.html Thank you for the support, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Flat is better than Nested
On Thu, 8 Sep 2011 21:39:47 -0500 "Ryan Strunk" wrote: > By the time I write this all into a file, the end user will never > even know this crazy hierarchy exists, but I will, and I don't like > it. Do I just need to get over it and realize that sometimes nested > is necessary, or is there a better way I might consider? There are two different problem you should consider here. The first is the MODEL STRUCTURE of your player. A model is a representation of something, so you really can't change the model structure that much from reality, as what you want is truly the opposite: you want to have the model as close as possible to the "something" you are representing. The other element to consider is the way you MANIPULATE your model, and this is the level at which you can operate to make your life easier. An example might clarify: suppose you are writing a very detailed simulation of the universe, and in it you have to model a neutron in your right big toe: your model could be something huge in terms of nested levels: Universe --> Milky way --> Aplha quadrant --> Solar system --> Planet Earth --> Continent --> Country --> County --> City --> District --> Building --> Floor --> Flat --> Room --> Person --> Limb --> Toe --> Cell --> Molecule --> Atom --> Nucleus --> Neutron. Now, if your simulation needs to know about stellar systems, continents, and all the rest, you really WANT to maintain all the levels of the hierarchy, because putting neutrons "flat" together with galaxies would make truly hard to write sane code. What you have to ask yourself is how you are going to manipulate your data. For example: when you are considering your neutron collisions with nearby subatomic particles do you really need to know about what galaxy your neutron is in? Probably not: all you need to know is about the nucleus of your atom. And when you are calculating the time a planet takes to go around it's star, do you really need to know about people living on it? Again: probably not. The trick for you would be to break down your hierarchy in sensible chunks, attaching to each bit of it the parts of code that are relevant at that resolution. So you could have a class "Nucleus", that knows about its parent molecule and its children particles and have methods like "get_atomic_number()", "decay()" or "bond_with()". And another class called "StellarSystem" knowing about its galaxy quadrant, its star(s) and its planet(s), having methods like "calculate_revolution()", "collapse()", etc... This is really what OOP is all about: you creating semi-independent objects which include only the information and methods needed at the level you are using them. Incidentally this won't only make things EASIER, it will also make them more FLEXIBLE/EASY-TO-MAINTAIN. Still working with the universe example: say that at some point (after you already wrote the code for planet Earth) you realise that other planets indeed are not organised in countries/counties/cities... If whenever you referred to an element in your simulation you included its entire hierarchy, you will be in trouble: you will have to modify your code everywhere you referred to something smaller than a planet. If you contrarily broke down your hierarchy and discover that on Alpha Prime they don't have administrative regions but just cities, all you will have to to is creating a new sister class "PlanetNoBorders" for the one ("PlanetWithRegions") that you used for the Earth, then you will be able to attach to it instantiations of the same City() class that you already used for planet Earth. In OOP this is called "programming to an interface", meaning that your code should ignore the real STRUCTURE of your data (the MODEL) and contrarily only know on how to MANIPULATE that data. Still using the universe example: if you need to access the list of cities on planets, you should make sure a "list_cities()" method is available both in "PlanetOriginal()" and "PlanetNoAdminBorders()" classes, and that they return data in the same format. You can then safely ignore if that specifc planet has or doesn't have countries on it. HTH, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How it is better than java
On Tue, 20 Sep 2011 10:27:12 +1000 Steven D'Aprano wrote: > There are three misunderstandings with that statement. > [snip] > There's also JPype, which claims to give full access to Java > libraries in Python. Now: this was one of the best write-ups on the subject I read. Concise, clear, documented. Nice way to start the day! :o /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need a bump in the right direction (network programming)
On Fri, 23 Sep 2011 03:20:53 -0400 Dave Angel wrote: > On 09/23/2011 01:15 AM, Cheeyung wrote: > > I'm creating a mobile application and I'm using python for a > > desktop server. However, I don't have access to a static IP on the > > desktop, but do have a website. Is it possible to connect from > > mobile -> http website -> desktop server and back? If I got you right, I would skip the website entirely. Just connect directly to your desktop from the mobile, using a dynamic DNS service. Maybe the bump you need could be: http://dnslookup.me/dynamic-dns/ HTH, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need a bump in the right direction (network programming)
On Fri, 23 Sep 2011 17:03:29 +0800 Cheeyung wrote: > >> On 09/23/2011 01:15 AM, Cheeyung wrote: > >>> I'm creating a mobile application and I'm using python for a > >>> desktop server. However, I don't have access to a static IP on the > >>> desktop, but do have a website. Is it possible to connect from > >>> mobile -> http website -> desktop server and back? > > If I got you right, I would skip the website entirely. Just connect > > directly to your desktop from the mobile, using a dynamic DNS > > service. Maybe the bump you need could be: > > http://dnslookup.me/dynamic-dns/ > > Hi, thanks for the reply. Dynamic DNS sounds like exactly what I > need, but just let me confirm if I understand it correctly. > > The mobile will connect to to the dynamic DNS service (ie. > example.dynamicdns.com), which will then redirect it to the desktop. > The desktop keeps the DDNS service updated using a script or > webclient etc. depending on the service. > > Did I get that right? I never used this service myself, but to the best of my knowledge yes, that's the way dynamic dns works. On another note: when replying to ML messages, remember to hit "reply all", otherwise your answer will be delivered to the author of the message only! :) /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with a recursive function
On Tue, 27 Sep 2011 14:32:00 -0400 c smith wrote: > hi list, > i understand the general idea of recursion and if I am following well > written code I can understand how it works, but when I try to write > it for myself I get a bit confused with the flow. > I was trying to turn an ackerman function into python code for > practice and I tried writing it like this: > #!/usr/bin/env python > > import sys, os > def ack(m,n): > > if m == 0: > return n+1 > elif m > 0 and n == 0: > ack(m-1,1) > elif m > 0 and n > 0: > ack(m-1,ack(m,n-1)) > > if __name__=='__main__': > sys.argv[1] = int(sys.argv[1]) > sys.argv[2] = int(sys.argv[2]) > > print ack(sys.argv[1], sys.argv[2]) > > The major problem, I think, is that I cant figure out where to turn > the args into ints. You did it right, just when you loaded them. What is not correct is to try to assign them to a property inside a standard library module. You should assign them to local variables (``m`` and ``n`` for example). > Also, does the second 'elif' make sense? I have am not familiar with the ackerman functions, but since you mentioned recursion, I suppose you wanted to recurse in those elif`s and return the result of a new call to the funtion. If that is the case, you could happily skip the "else" part of "elif" because if the ``if`` code will run, the interpreter will never reach the ``elif`` line. > I am not sure if the function can take itself as an argument. > thanks for any suggestions, this list has been a big help. Here's the code readapted (but verify it still does what is intended to!): #!/usr/bin/env python import sys, os def ack(m,n): if m == 0: return n+1 if m > 0: if n == 0: return ack(m-1,1) if n > 0: return ack(m-1,ack(m,n-1)) raise BaseException('Something is wrong here!') if __name__=='__main__': m = int(sys.argv[1]) n = int(sys.argv[2]) print ack(m, n) HTH! /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Why subclassing exceptions?
On Wed, 28 Sep 2011 09:58:49 +1000 Steven D'Aprano wrote: > Mac Ryan wrote: > > > raise BaseException('Something is wrong here!') > > Never raise BaseException directly! BaseException is the very top of > the exception hierarchy, you should raise the *most* specific > exception you can, not the least specific. BaseException isn't even > just for errors, it's also for flow control exceptions like > StopIteration . Fair enough! :) I just put that line to signal that there were cases that weren't catch by the series of ``if``, but nevertheless you are right. **I would like to know more on the rationale behind this guidelines, though.** I explain: I already knew before that I should subclass exceptions, nevertheless I very seldom do, as I feel like they are just taking space on my screen doing nothing useful. All I need to do is often just print out a useful message, so I find that >>> raise StandardError('This value should be True.') does the job in a much more elegant way than: >>> class ShouldBeTrueError(StandardError): ... ... ''' ... Custom Error triggered in case a value should be True. ... ''' ... ... pass ... >>> raise ShouldBeTrueError('Doh! An error!') Ok, I already hear some of you screaming out loud "Anathema!!" ;) ...yet could somebody please clarify why should I bother subclassing? [I'm positive there is a good reason, but in all honesty I can't imagine which one...]. Thanks, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why subclassing exceptions?
On Wed, 28 Sep 2011 09:03:11 +0100 Alan Gauld wrote: > Remember that when handling exceptions we should be trying > to recover the situation not just bombing with an error message. > Exceptions should not be thought of as purely about > messages, they are opportunities to recover the situation without the > user even being aware that something went wrong. Only when recovery > is impossible should we bomb out with a message. Thank you Alan for the quick response. I totally see your logic, and surely I can't (nor I wish to) argue with it in the context you illustrated. I have to say - however - that even after a few years of python development I seldom use exceptions that way: in fact I can only remember having subclassed error classes once, when I wrote a library that was intended to be used by third-parties (for the exact same reasons that you exemplified). In all other cases (code that doesn't expose an API to third parties) I consider that either my program works (and thus it can handle all possible situations) or it does not, in which case - given that nothing should silently fail - I'm happy for it to scream out loud with a raise BaseException(''). In fact, I use exceptions only when I can't write an ``assert`` statement concise enough. In the original code to which you initially reacted I used an exception simply because it was more concise to put it under the else clause rather then writing an ``assert`` statement with all the if/else possibility it would have needed. Is there any reason for which you (or anybody on the list, of course) think I should avoid doing this? /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why subclassing exceptions?
On Wed, 28 Sep 2011 10:15:07 -0400 "Prasad, Ramit" wrote: > >If you are using asserts for data validation, then your code is > >broken. The caller can disable every single assert, and hence remove > >your data validation, by simply passing a command line switch when > >calling your program. > > To be fair, there are plenty of situations where someone has enough > control of their execution environment to prevent that from > happening. I agree on principle and for readability/maintainability; > if I saw that I would be highly confused as to why asserts were > everywhere. Thank you Alan, Steve, Ramit for all your answers, very appreciated and useful. I would like to point out that I am not using ``assert`` for data validation. I am using it to understand if my code works. The reason why I prefer asserts over exceptions is just what you pointed out. Keeping building on Steve's simile: when I use asserts in my code, I'm still at the car factory. I'm not trying to communicate anything to a potential driver: I'm just trying to prevent myself to say "the car is ready" if there is a major flow in its design. In other words: rather than creating a specific "EngineerForgotToDesignEngine" warning light, I want the engineer to realise at a much earlier stage that she does need to put an engine on the car before the car is ready for prime time. Maybe the initial example that generated this thread was misleading, as a function is a typical example of a code that never knows what parameters will be passed in. All that said, I totally see your point and I swear that from now on I will give a deeper thought to what to write after the word "raise"! :) Thank you very much once more, /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Mailing list archive oddity?
On Thu, 29 Sep 2011 23:08:19 +0200 Hugo Arts wrote: > * someone from the future is in need of python help and is sending > messages back in time. I told Guido that Python version 5.2 sucked, but he wouldn't / will not listen! :-/ /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] basic problem
On Thu, 6 Oct 2011 22:11:37 + ADRIAN KELLY wrote: > can someone spell out to me in (simply if possible) what this > programme is doing. i understand the concept of the "for" loop and > what its doing with the message the user enters. i just cant > understand the VOWELS and how it keeps adding 1 letter to the > message. thanks for looking A > > > # this programme will adding something to everything the user > #types by using a for loop This program might have been intended to to so, but it actually does not. Have you tried running it? > #set values > new_message=" " > VOWELS="AEIOU" This last line defines what vowels are. It defines it as a string, but keep in mind that strings in python can be both handled like individual object like in "print(text)" or like an ordered collection of letters, like in "for letter in message" (more on this in a moment). > message=raw_input ("Enter a message: ") > for letter in message: This is an example of the second way of handling strings (the proper name for what is going on here is "iteration"): the last line will instruct python to take one letter at a time, from left to right, from the message, and do with it whatever is indented here below. > if letter.lower() not in VOWELS: This is still an example of handling strings as ordered collections of letters: basically it says to check if any letter in "VOWELS" is the same as the letter being processed, in lower case. Actually this is also an example of pointless operation: VOWELS has been defined as "AEIOU" which are all capital letters. Since the comparison is done between a letter from the user input in lower case ("letter.lower()") the condition will always be True, so this line might well not be there. > new_message = new_message+letter The idea behind this line is that you keep adding the letter to the end of the message. The line works, but it's not an example of good python code. An improvement might be to use: new_message += letter which is more common and more readable. But in python one seldom does this kind of operation because strings are "immutable objects". In other words even if the logic behind is to "add a character" what is really going on behind the scenes is that the old version of "new_message" is destroyed, and a new one will take its place. While this is not a problem in this simple example, it is an expensive process, so often it is preferable to store the various "additions" in a list and merge them together only once, at the very end. The syntax is: ''.join(['a', 'b', 'c']) so in your program you would probably initialise an empty list first, and then append the letters at each loop: pool = [] for letter in message: pool.append(letter) print ''.join(pool) HTH! /mac ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor