Re: [Tutor] print 'hello world' - invalid syntax
On Sun, May 20, 2012 at 1:08 PM, Quidam S-enfuit wrote: > > I have installed python on the windows 7 machine. (Tried 64 bit version > also; same error). > I tried print "Hello world" and print 'hello world'. It stated syntax > error!?... > Thanks. > ===copied from python (interactive command) /pasted > below== > Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] > on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> print 'hello world' > File "", line 1 > print 'hello world' > ^ > SyntaxError: invalid syntax > > ==end I am starting to learn Python as well. Apparently one of the significant changes from Python 2.x versions to the new Python 3.x versions is that print is now treated as a function. So instead try: print('hello world') I think that should work for your version of Python. -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] While learning Py: To IDE or not to IDE?
Programming background; 1975-1978: FORTRAN, BASIC, some machine language/assembler. 1988: A summer of FORTRAN. Post-1988: No programming until past 1.5 yr. FORTRAN was used during pursuit of physics degree. Others while playing around developing games for minicomputers. Structured programming paradigm the only one I've used. Currently have been doing scripting in a custom scripting environment at work to make my life easier. This is on Solaris-based systems. Have recently augmented the custom scripting environment with Perl scripting to give me more power and error-checking capabilities (Others have started to use my scripts. They don't always use them as I intended.). Perl is a new language for me. Goals: Learn Python. While learning Python, learn all of the good C.Sc. stuff that I should have learned the first go-around, Learn Java and C/C++. Reevaluate. At home where I will be doing the brunt of my study, I am working on a W7 laptop. Currently continue to work on scripting projects at work, replacing Perl scripts with Python scripts. My wife, who is a Montessori teacher, has immediate need of programs for her students. Have currently outlined a design for a program to drill spelling words, which will have to have audio record/playback capabilities. Hope to get this and others done this summer before the new school year starts. I am certain that my wife will continue to have new projects for me as I complete the current ones. Hope to have educational software solutions to my wife's requests that are usable whether the students are at home or in class. Finally to the question: With the stated goals above, would it be better to invest time now at the front-end in learning a powerful IDE, or am I better served, while learning Python, to stick with IDLE and the shell and worry about an IDE later? I am willing to invest time now on learning an IDE if it will save me time overall. IF it would be beneficial now to learn an IDE, then it begs the question as to whether I should search for the best IDE for Python, then later the best one for Java, etc., or, instead, look for the best one that can handle all of the languages I plan to learn and use. Thanks for any guidance you can provide! -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Teaching an 8-year-old programming.
This is, in a sense, a related question to the ones I just posted. While observing me studying programming, my son has become interested in learning how to program as well. I have given him a very old Gateway PC to play around with. It was new when W95 came out. I have started him out with QBASIC, which comes with W95. He seems to be doing fine, but I am wondering if this is the best way to start him in the world of programming? Any thoughts about this? Thanks! -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Teaching an 8-year-old programming.
On Sun, May 20, 2012 at 4:15 PM, Devin Jeanpierre wrote: > I've heard remarkable things about http://www.programbydesign.org/ , > but it's aimed at students a little older. Its design might help you; > although, it also probably depends on motivation / what you want to > teach. > > Anyway, that's the best I can offer. Good luck! It sounds like you're > in for a fun time. :) > > -- Devin Thanks for the link. It looks interesting, but I'm not sure it is the way to go currently for my son. However, it gives me some ideas for my wife's class, which covers 7th through 9th grades in a single classroom. There seem to be many, ... , many thoughts on how to best teach programming to kids! I am currently thinking about "Invent Your Own Computer Games with Python" by Al Sweigart. His thought is to give kids complete, workable code for a real game and let them fool around with it. This might work! I did something similar starting out with my son using QBASIC, giving him a brief program that played music. He seemed to have quite a lot of fun fooling around with different permutations of the commands. Later, when I introduced him to some new commands, like generating random numbers, he combined a number guessing game with his self-composed musical theme. Has anyone experience using this book? -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While learning Py: To IDE or not to IDE?
On Sun, May 20, 2012 at 4:44 PM, Brian van den Broek wrote: > These are close to religious questions :-) > > With you polyglot agenda, I would say you would be much better off to learn > a powerful multipurpose editor well than to try to find the best of breed of > each class of special purpose tool. > > There are three basic choice: emacs, vi or vim, and everything else. There > is widespread, though not uniform, consensus that The One True Editor is one > of emacs and vi. After that, the rest is flamewars. > > I am an emacist, myself. But some of my best friends are vimists. I gather, then, that you feel my time would be well-spent now to learn a good editor/IDE now, rather than continue with IDLE? I did not intend to start a holy war on the best editor/IDE with my questions! ~(:>)) But since you brought it up, I'll ask a somewhat more general question: Why do you prefer an editor instead of a graphical IDE? I have limited experience with Emacs as I finally installed it on my PC at work to avoid having Windows-style end-of-line characters messing up my scripts which were to run in an UNIX environment. I can see potential there, but as my future projects get larger and more involved will it be able to do everything I would want it to do? Would I find myself wanting a full-fledged IDE? I don't have enough technical knowledge to answer these questions right now. Your thoughts? Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Teaching an 8-year-old programming.
On Sun, May 20, 2012 at 6:16 PM, Robert Sjoblom wrote: > "Snake wrangling for kids" is pretty good for teaching Python; it's > also free (which is a bonus): > http://www.briggs.net.nz/snake-wrangling-for-kids.html > Thanks everyone for all of the good suggestions! After spending most of the day looking at them I think that (for us) "Snake Wrangling for Kids" is the winner. It is a very readable book that I think Jeremy will be able to follow. It also incorporates the suggestions of Bill and Alan in using Turtle Graphics, which I think (after playing with it myself today) is pretty cool. Now I just have to get Jeremy some updated hardware, so that he can both connect to the Internet and run Python 3. This is an obvious opportunity to convince my wife to allow me to update "my" hardware, so that both she and Jeremy can update theirs. -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Optimally configuring Emacs for W7-64bit and Python
Many thanks for all of the helpful input to my original questions. The deciding factors came down to the fact that GNU Emacs, vintage year 2001, is available on the Sun Blade at work, I already own the book "Learning GNU Emacs" and it would be nice to have my fingers trained the same way for both work and home study. What is the best way for me to get my W7-64bit laptop configured for Python programming? My consultations with the Google oracle have yielded inconclusive results this evening, though I confess I am quite tired, so I may be missing the obvious. -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Optimally configuring Emacs for W7-64bit and Python
> Install python mode. > Learn how to get the python shell running inside emacs. > Learn how to get a cmd shell running inside emacs > Learn how to do split windows On some of the pages I recall looking at, it was mentioned that Emacs comes with two major modes for Python. It was not clear to me which one should be preferred. Also, mention was made of several extensions to Emacs, that provided things like code completion, etc. It was not clear to me if these would work with Windows and it was not clear to me if these were desirable or not. So, I was curious about whether anyone had definite recommendations about these things. > One extra that I would strongly encourage for working with Python on windows > is to supplement the emacs debugger mode with winpdb. It can be had for > Linux too, I don't know about Solaris. But I think your Solaris is non GUI > based anyway as I recall? So that won't matter. Now I just looked at winpdb and it states that it must have wxPython installed. So, I went to its website and the latest version is 2.8.12.1. If the versions of wxPython parallels that of Python then this means that version 3.x won't be supported. Is this correct? Now it did mention that there was a console version of winpdb that did not require wxPython, but would this be what you intended for me, Alan? The Solaris at work is Solaris 8 and has many GUI-based apps, but I am forced to use whatever is on the computers. Normally, we are not allowed to add any software to these workstations as they are radiation oncology planning stations with associated FDA approvals "as sold". At the main site where I work we have three planning stations, one an 810X, one a Sun Blade and the other is even older hardware (I can't remember its exact designation.). The 810X is running on Solaris 10 while the latter two have been upgraded to Solaris 8. The Solaris 8 machines do not have Python installed! Emacs is version 20.7.1 and the Perl I've been using is version 5.005_03. The Solaris 10 machine has Python 2.4.4, but this is of no use to me as the same scripts have to be able to run on all three machines. However, there are plans after July 1st to upgrade all three machines to thin clients connected to an enterprise server. Hopefully if this actually happens then Python will be available on everything. Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Optimally configuring Emacs for W7-64bit and Python
but I will not be able to provide much (any?) help in the immediate future. > > (If emacs seems like you will stick to it, do have a look at orgmode.) > Brian, does org-mode amount to a personal information manager? What are the things you especially like about it? Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [OT] Re: Optimally configuring Emacs for W7-64bit and Python
> I'd be happy to answer any further questions you might have. But, 1) I won't > be prompt due to travel, and 2) if you write about org-mode, let us go > off-list as we've strayed from tutor's purpose. > Brian, my primary question(s) are how to best configure Emacs for Python development. Is the existing major mode for Python sufficient for my needs in your opinion? When I have done some Googling, another major mode for Python has been mentioned. However, when I go to the Emacs help manual mention is only made of one. There has also been mention of what I presume are external Lisp modules that add additional functionality to either Python major mode. Are any of these worth pursuing? What type of configuration do you use? Currently I have deferred Python study to work through a few chapters of my Emacs books, so I can start to get comfortable with the keyboard movement and editing commands. Once I feel semi-comfortable with these then I will more thoroughly investigate configuration options for Python within Emacs. Hope you are enjoying your travel time! -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Civil discourse from a newbie's perspective
I have been following the discussions here since middle-May of this year. I have gathered that the volunteers strongly value precision of speech and proper formatting of posts and especially making a strong effort to solve one's problem(s) before bringing it(them) up here for help. I think I understand the frustrations that can arise when newcomer after newcomer continue to repeat the same basic posting errors, seemingly without end (May I never do the same!). However, I think that extra care may be needed in dealing with newbies who may only be taking a programming course using Python because of curriculum requirements. I'm sure I am stating the obvious to most of you, but, nonetheless, I think it is still worth saying (Again?). How one of you phrase your meant-to-be-helpful response can inadvertently prove crushing to someone who is very insecure in their programming knowledge, and in some instances, apparently, incite them to profanity. In my first post here I inappropriately used the phrase, "begs the question." I soon was informed of the error of my ways! While educational (And, I confess, somewhat irritating.), these clarifications had nothing to do with the actual intent of my post. I shrugged it off, examined the comments and links about my offending phrase, and went on to appreciate the valuable helpful comments that I did receive on what I was really asking about. I only bring this up as a concrete example of an instance that might have caused a newbie to go elsewhere in frustration and anger, if I were thin-skinned about it. I am hesitant in even bringing these thoughts up, but it seems recently there has been a rash of anger, profanity and hurt feelings. Of course this is my subjective impression, which may be colored by my lack of a thick skin. But I DO want to say, that I greatly value the efforts of the volunteers who strive to be so helpful and demonstrate repeatedly great patience in the face of what clearly must, at times, be extremely frustrating. But please exercise precision in your communications with overly sensitive, frustrated or tentative newbies! -- Cheers! boB Stepp ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Civil discourse from a newbie's perspective
On Tue, Oct 2, 2012 at 7:25 AM, Francois Dion wrote: > Even worse would be the case of a young aficionado. It is very hard > to infer the age of a person from a post. As Python is making inroads > in the K-12 sector and through inexpensive computing platforms such as > OLPC, the Raspberry Pi and the like, there is a potential to be > interacting with some very young programmers. I think right now the > bulk of them are sticking to forums (definitely the case with the > Raspberry Pi), but it is inevitable that the makeup of the readership > of this list will change. What will happen when a 9 year old kid who > loves computers is turned away by a cutting remark or heavy criticism? > Similarly, one should be considerate as to the language used. > I am glad that you brought this point up. As some may recall from my first post, I mentioned that I was trying to encourage my 9-year old son (then 8 years old) to explore programming. As part of that effort I have set him up with his own PC with Internet access. We try to keep him well-supervised, but he is gaining in confidence in conducting searches for answers to his own questions. If he does ever "click" in his interest in Python, I could easily see him exploring this forum for answers. However, I would hate for him to be exposed to some of the "rhetoric" that has arisen here recently. On the other hand, I cannot perfectly protect him from everything and the information accessible from the Internet is of too much utility to forbid him its access. I will just prepare myself for some interesting questions in the near future! ~(:>)) -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Civil discourse from a newbie's perspective
Leam, On Tue, Oct 2, 2012 at 4:04 AM, leam hall wrote: > > Does the welcome e-mail cover any of the recommended behavior? Are there > easier ways to request participation within guidelines? > Not only does the welcome message cover this, apparently when I posted my message that started this thread I received a copy automatically of the same message, repackaged: "Auto-response for your message to the "Tutor" mailing list Python/tutor@python.org x tutor-boun...@python.org 8:34 PM (21 hours ago) to me Your message for tutor@python.org, the Python programming tutor list, has been received and is being delivered. This automated response is sent to those of you new to the Tutor list, to point out a few resources that can help with answering your own questions, or improve the chances of getting a useful answer from the other subscribers. [...]" This is the beginning of exactly the same message I received when I first joined this mailing list. Honestly, newbie or not, I do not understand why many of the posts from newcomers so routinely violate the contents of this welcome message. I know I am trying to abide by them. Laziness? Difficulties with English comprehension? Sheer stubbornness? Or something more innocent? I have no clue. But fellow newbies: Please (!!!) read the contents of the welcome message. It spells out in great detail the expectations for posting here and might help you get your questions answered much more quickly and efficiently! Cheers! boB Stepp ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Civil discourse from a newbie's perspective
On Tue, Oct 2, 2012 at 6:25 PM, boB Stepp wrote: > This is the beginning of exactly the same message I received when I > first joined this mailing list. Honestly, newbie or not, I do not > understand why many of the posts from newcomers so routinely violate > the contents of this welcome message. I know I am trying to abide by > them. Laziness? Difficulties with English comprehension? Sheer > stubbornness? Or something more innocent? I have no clue. But fellow > newbies: Please (!!!) read the contents of the welcome message. It > spells out in great detail the expectations for posting here and might > help you get your questions answered much more quickly and > efficiently! > On my way to Walmart and back it occurred to me that what I wrote above is somewhat harsh. I did not mean it to be so! However, it also occurred to me that maybe what I have received and am receiving is not reaching all newcomers to this list. In fact, it is NOT the welcome letter that contains the rules for good posting and tips on answering one's own questions, but an auto-generated email in response to a newcomer's first few posts. Instead of posting a copy of the email sent to me, see http://code.activestate.com/lists/python-tutor/88777/ , which appears to contain the full text of what I have received. I hope it is helpful to anyone who has not received it for some reason or other. -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Why difference between printing string & typing its object reference at the prompt?
After much diddling around I have finally settled on a text to study (Programming in Python 3, 2nd edition, by Mark Summerfield) and have defaulted to using IDLE, deferring worrying about editors/IDEs until I feel comfortable in Python. I am puzzled by the results of the following: >>> x = "Test" >>> x 'Test' >>> print(x) Test I understand that 'Test' is the stored value in memory where the single quotes designate the value as being a string data type. So it makes sense to me that just typing the object reference for the string results in including the single quotes. But why does the print() strip the quotes off? Is just as simple as normally people when performing a print just want the unadorned text, so that is the behavior built into the print function? Or is there something more subtle going on that I am totally missing? If an explanation is in one of my several books, it is currently eluding me. -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?
Thanks to all who responded. There was much more going on here than I ever would have suspected. I am glad I asked the questions I did. This has been very informative. On Tue, Oct 2, 2012 at 11:53 PM, Dave Angel wrote: > > There are two operations supported by (most) objects that produce a > string. One is exemplified by the str() function, which converts an > object to a string. That's the one called implicitly by print(). This > form just represents the data, in the form most likely to be needed by > the end user. What happens if str() or repr() is not supported by a particular object? Is an exception thrown, an empty string returned or something else I am not imagining? > > The other operation is repr(), which attempts to produce a string that > could be used in a program to reproduce the actual object. So a repr() > will have quote marks artificially added, or brackets, or commas, or > whatever seems appropriate for the particular object. This is intended > for the programmer's use, not for the end user. What larger phrase does "repr" stand for? My text mentions "representational form" later in the book, which sounds similar in concept to what you are discussing. [...] > Your question was about string objects, but I tried to make the > explanation as generic as possible. Those two functions, str() and > repr(), are used, or implied in many places. For example, if you print > a list, it'll call str() on the whole list. But the list object's logic > will in turn call repr() on each of its elements, and put the whole > thing together with braces and commas. > As I go along in my study of Python will it become clear to me when and how repr() and str() are being "...used, or implied in many places"? Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?
On Wed, Oct 3, 2012 at 1:38 AM, Steven D'Aprano wrote: > The long answer is a bit more subtle, and rather long. I had initial suspicions this would be the case Thanks for yours and Dave's detailed exposition! [...] > Python is no different: words, text if you will, that are part of the > code are written as normal: > > # source code > class Test: > pass > > x = Test # Test here refers to the variable Test, a class > > But to create a string object, you use quotation marks to tell Python > that this is data, not code, please create a string object: > > x = "Test" # Test here refers to a string, which is data > > Notice that the quotation marks are *delimiters*, they mark the start > and end of the string, but aren't part of the string in any way. Python > knows that the object is a string because you put it in string > delimiters, but the delimiters are not part of the string. I was not sure if the quotes were considered part of the string or not. Thanks for the clarification. > Now, take a step back and consider objects in general. There are two > things we might like to do to an arbitrary object: > > * display the object, which implicitly means turning it into a > string, or at least getting some representation of that object > as a string; > > * convert the object into a string. > > Python has two built-in functions for that: > > * repr, which takes any object and returns a string that represents > that object; > > * str, which tries to convert an object into a string, if that makes > sense. > > Often those will do the same thing. For example: > > py> str(42) == repr(42) == "42" > True > > But not always. For example: > > py> from decimal import Decimal as D > py> x = D("1.23") > py> print(str(x)) > 1.23 > py> print(repr(x)) > Decimal('1.23') These contrasting examples are very illuminating. So in print(str(x)) the object, D("1.23"), is being converted into a readable string, which makes the most sense as 1.23. But print(repr(x)) is giving a string representation of the object as code, which is more than just 1.23, the Decimal('1.23'). Am I understanding this correctly? > Unfortunately, the difference between str() and repr() is kind of > arbitrary and depends on the object. str() is supposed to return a > "human-readable" version of the object, for display, while repr() is > supposed to return a string which would work as code, but those are more > guidelines than hard rules. Will these fine distinctions be easy for me to pick up on as I progress in my Python studies? I suspect that I am going to have to experiment with str() and repr() in each new situation to see what results. > So we have two different ways of converting an object to a string. But > strings themselves are objects too. What happens there? > > py> s = "Hello world" # remember the quotes are delimiters, not part of the > string > py> print(str(s)) > Hello world > py> print(repr(s)) > 'Hello world' > > str() of a string is unchanged (and why shouldn't it be? it's already a > string, there's nothing to convert). > > But repr() of a string creates a new string showing the representation > of the original string, that is, what you would need to type in source > code to make that string. That means: > > 1) wrap the whole thing in delimiters (quotation marks) > 2) escaping special characters like tabs, newlines, and binary >characters. As to point 2), will repr() insert "\" (I am assuming Python uses a backslash like other languages to escape. I have not read about this in Python yet.) for these special characters? Will str() do the same? > Notice that the string returned by repr() includes quote marks as part > of the new string. Given the s above: > > py> t = repr(s) > py> print(t) > 'Hello world' > py> t > "'Hello world'" > > This tells us that the new string t includes single quote marks as the > first and last character, so when you print it, the single quote marks > are included in the output. But when you just display t interactively > (see below), the delimiters are shown. Another great example. I probably would have overlooked this. > Now, at the interactive interpreter, evaluating an object on its own > without saving the result anywhere displays the repr() to the screen. > Why repr()? Well, why not? The decision was somewhat arbitrary. So the designers of Python made this decision. I guess it had to be one way or the other. > print, on the other hand, displays the str() of the object directly to > the screen. For strings, that means the delimiters are not shown, > because they are not part of the string itself. Why str() rather than > repr()? Because that's what people mostly want, and if you want the > other, you can just say print(repr(obj)). So in the end it is a simple choice to give the users what they want and are already used to. > > Does this help, or are you more confused than ever? > This has been incredibly useful! Many thanks!! boB ___
Re: [Tutor] string rules for 'number'
On Oct 7, 2012 12:47 PM, "Arnej Duranovic" wrote: > > When I type this in the python idle shell ( version 3...) : > '0' <= '10' <= '9' > The interpreter evaluates this as true, WHY? 10 is greater than 0 but not 9 Since they are strings it looks at these character by character. Since '0' < '1' < '9' , the 0 in '10' has no effect on the order. Compare 'a' < 'ba' < 'i' . boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?
Steve, On Thu, Oct 4, 2012 at 6:28 AM, Steven D'Aprano wrote: > > Now, ask me about *raw strings*, and the difference between Unicode > and byte strings :) How can I resist asking! I am not in chapter 2 of my study text yet, but looking ahead raw strings seem to be a method of declaring everything within the quotes to be a literal string character including the backslash escape character. Apparently this is designated by using an r before the very first quote. Can this quote be single, double or triple? I am not up (yet) on the details of Unicode that Python 3 defaults to for strings, but I believe I comprehend the general concept. Looking at the string escape table of chapter 2 it appears that Unicode characters can be either 16-bit or 32-bit. That must be a lot of potential characters! It will be interesting to look up the full Unicode tables. Quickly scanning the comparing strings section, I wonder if I should have been so quick to jump in with a couple of responses to the other thread going on recently! I don't see a mention of byte strings mentioned in the index of my text. Are these just the ASCII character set? Since I have not made it formally into this chapter yet, I don't really have specific questions, but I would be interested in anything you are willing to relate on these topics to complete my introduction to strings in Python. Or we can wait until I do get into the data types chapter that looks at these topics in detail and have specific questions. -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?
On Tue, Oct 9, 2012 at 4:29 AM, eryksun wrote: > Python 3 lets you use any Unicode letter as an identifier, including > letter modifiers ("Lm") and number letters ("Nl"). For example: > > >>> aꘌꘌb = True > >>> aꘌꘌb > True > > >>> Ⅰ, Ⅱ, Ⅲ, Ⅳ, Ⅴ = range(1, 6) > >>> Ⅰ, Ⅱ, Ⅲ, Ⅳ, Ⅴ > (1, 2, 3, 4, 5) Is doing this considered good programming practice? I recall there was a recent discussion about using the actual characters in formulas instead of descriptive names, where this would make more sense to people knowledgeable in the field using the formulas; however, descriptive names might be better for those who don't have that specialty knowledge. Is there a Python community consensus on how and when it is appropriate (if ever) to use Unicode characters as identifiers? > A potential gotcha in Unicode is the design choice to have both > [C]omposed and [D]ecomposed forms of characters. For example: > > >>> from unicodedata import name, normalize > > >>> s1 = "ü" > >>> name(s1) > 'LATIN SMALL LETTER U WITH DIAERESIS' > > >>> s2 = normalize("NFD", s1) > >>> list(map(name, s2)) > ['LATIN SMALL LETTER U', 'COMBINING DIAERESIS'] > > These combine as one glyph when printed: > > >>> print(s2) > ü > > Different forms of the 'same' character won't compare as equal unless > you first normalize them to the same form: > > >>> s1 == s2 > False > >>> normalize("NFC", s1) == normalize("NFC", s2) > True This looks to make alphabetical sorting potentially much more complex. I will have to give this some thought once I know more. >> I don't see a mention of byte strings mentioned in the index of my >> text. Are these just the ASCII character set? After seeing your explanation below, I was able to find the relevant material in my book. It was under "bytes type" and "bytearray type". For some reason these categories did not "click" in my head as what Steve was addressing. > A bytes object (and its mutable cousin bytearray) is a sequence of > numbers, each in the range of a byte (0-255). bytes literals start > with b, such as b'spam' and can only use ASCII characters, as does the > repr of bytes. Slicing returns a new bytes object, but an index or > iteration returns integer values: > > >>> b'spam'[:3] > b'spa' > >>> b'spam'[0] > 115 > >>> list(b'spam') > [115, 112, 97, 109] > > bytes have string methods as a convenience, such as find, split, and > partition. They also have the method decode(), which uses a specified > encoding such as "utf-8" to create a string from an encoded bytes > sequence. What is the intended use of byte types? Thanks! This continues to be quite informative and this thread is greatly helping me to make better sense of the information that I am self-studying. -- Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Objects, object references, object values and memory addresses
>From Programming in Python 3, 2nd edition (p. 22-23): >>> a = ["Retention", 3, None] >>> b = ["Retention", 3, None] >>> a is b False >>> b = a >>> a is b True My current understanding is as follows: On the first two lines, two separate objects are defined, stored in two separate blocks of memory. These two objects just happen to have the same value, ["Retention", 3, None], stored in two separate locations. a and b, the object references (Variables are what I used to call these.), store these two separate memory locations. Thus a is b is false. However, when the line b = a is implemented, b now references the same object (memory location) as a, which now causes a is b to be true. Is my understanding correct? On the next page the author states (after giving a string example where a and b each are assigned the string "many paths", similar to the example above): "In some cases, comparing the identity of two strings or numbers--for example, using a is b--will return True, even if each has been assigned separately as we did here. This is because some implementations of Python will reuse the same object (since the value is the same and is immutable) for the sake of efficiency..." I ask: Which implementations of Python do this? In trying to make any code I write portable across as many platforms as possible, should I avoid using the identity operator, is (and its opposite, is not), except when I wish to compare to None? -- Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] IDLE shell indentation?
>>> if zero: print(zero) else: print(phrase) Wild Swans by Jung Chang >>> Is there some special way for typing in multiline blocks of code into the shell in IDLE? The above works, but it bothers me that "else" does not line up with "if". Also, in the IDLE shell the "p" in "print" actually lines up under the "e" in "zero". However when I copied from IDLE and pasted into gmail, this alignment was changed. I am guessing it is because gmail is not using a fixed-width font. And I have yet to figure out how to get it to use one when in plaintext mode. Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IDLE shell indentation?
On Thu, Oct 18, 2012 at 9:46 PM, eryksun wrote: > You're right that the alignment changed because of the font rendering > of the tab character. In Firefox I use the following to get a > monospace font in Gmail: > > http://userstyles.org/styles/15618/gmail-monospace-font-for-body-messages-textarea It did not occur to me to search outside of the gmail/chrome help as I felt sure that monospace capability had to be built-in! Thanks for pointing me elsewhere. Now all is swell. > As to your main question, I use exec: > > >>> zero, phrase = '', 'spam' > >>> exec(''' > if zero: > print(zero) > else: > print(phrase) > ''') > spam This does keep the alignment I desire; however, IDLE shell's autoindent feature goes away inside the exec function. Further, my tab, which is set to 4 spaces, becomes 8 spaces at the indent; apparently the tab takes effect after where ">>> " would normally occur. Of course I can just manually type the four spaces. Alas! Perfection here is apparently unattainable! ~(:>)) boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to print ALL contents of a scrolled Tkinter window?
Solaris 10, Python 2.4.4 Thanks to earlier help from this list, I can now print a particular Tkinter-generated window. But this will only print what is currently viewable on the screen. In the case of scrolled information that is currently outside the viewing area, it would be missed by such a print (Using OS import command, as Peter demonstrated.). This type of print functionality appears in everyday software products, but it is not clear to me (Yet!) how to approach this problem. My initial thoughts are along the lines of: 1) Determine how many rows of information appear in the viewing area. 2) Determine how many total rows of information exist to be printed. 3) Figure out how to programmatically do a *manual* scroll to bring up the hidden scrolled information. 4) Repeatedly apply the printing method. While I can probably make this approach work (It *seems* conceptually simple.), I cannot help but feel there is a much better way... I intend to scour my available Tkinter documentation to see if there are root window level and scrolled area commands that might suggest another approach. And what I am doing now, seeking your collective wisdom... Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to print ALL contents of a scrolled Tkinter window?
On Fri, Apr 17, 2015 at 9:29 AM, Laura Creighton wrote: >>While I can probably make this >>approach work (It *seems* conceptually simple.), I cannot help but >>feel there is a much better way... > > Tkinter is very old software. This sort of scrolling you want was > in no way common when Tkinter was new. For things like this, I > just use kivy, which has the advantage that is runs under IOS and > Android out of the box. > > The whole point of kivy is to create better, new paradigm user interfaces, > where scrolling surfaces are built-in. > > It may be faster for you to reimplement what you have in kivy than to > try to get Tkinter to do what you want. Alas! I am not allowed to install any new software on these systems (Which use Python 2.4.4 or 2.6.4.). So I am stuck with whatever tools are installed by default, and that does not include your suggestion. However, I will look into kivy for my at-home studies/projects! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to print ALL contents of a scrolled Tkinter window?
On Fri, Apr 17, 2015 at 7:04 PM, Laura Creighton wrote: > In a message of Fri, 17 Apr 2015 21:06:35 +0100, Alan Gauld writes: >>On 17/04/15 15:29, Laura Creighton wrote: >> >>> just use kivy, which has the advantage that is runs under IOS and >>> Android out of the box. >> >>But does Kivy support hard copy printing? >>That's pretty unusual behaviour on >>tablets/phones. > > Every kivy app lives in precisely one window. This window has a screenshot > method. You can bind it to a button, and you will get a png of exactly > what your app looks like. > > Also, every widget has an export_to_png method which you can use to > capture the widget and its children. Have these types of methods ever been considered for tkinter? They would go a long way to giving people a way to print, while not getting into a lot of OS hassle. In my particular scenario I would desire the ability to output both postscript and pdf, though if I have the first it is easy to get the latter. boB Stepp ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Star imports, was Re: How to get a Tkinter window to print a color copy of itself as a .pdf file?
On Thu, Apr 16, 2015 at 2:54 AM, Peter Otten <__pete...@web.de> wrote: > boB Stepp wrote: > >>> import Tkinter as tk >> >> Question: I have been using "from Tkinter import *" as suggested in >> "Programming Python" by Lutz. He remarks that unlike other situations, >> this is generally safe with Tkinter. Is there a benefit to doing the >> import as you have? > > It's a stylistic preference: I like to keep namespaces separate. After reading your full post, you have convinced *me* this is more than stylistic preference. > When I make an exception, typically for generic functionality like > > contextmanager, groupby, namedtuple, defaultdict... > > I import these in a controlled way with > > from collections import defaultdict > from itertools import islice, zip_longest Making it very clear to anyone who comes later. > etc., use them as "pseudo-builtins", and avoid writing functions with the > same name myself. By contrast I have no clear idea of what's in the tkinter > package and might write my own getint() function, say, thus forcing a reader > to scan the complete module to learn which getint() is used. This in particular applies to me at my current stage of learning as I have only scattered knowledge of all that is in the tkinter package. > This is a general problem of star imports; when you overwrite an imported > name you typically don't care or even know about that name in the imported > module. When you read your module later to fix or amend something your > knowledge may have grown, and you expect the imported function where the > custom function is used. This confusion becomes even more likely when a > second developer is involved. You are so persuasive here that forthwith I will change to a substantially explicit format of importing! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How (not!) lengthy should functions be?
On Thu, Apr 16, 2015 at 1:43 PM, Peter Otten <__pete...@web.de> wrote: > However, there's more to it. You are working in an environment where people > may be harmed if you get your numbers wrong, and nothing hinders you to swap > the arguments in your percent2Gy() function or even pass it a length and an > amount of dollars. You need measures to make this unlikely. I am attempting to do this. In a large sense, the whole purpose of my program is to evaluate what the planner has already done. The planner at this point would normally believe he has a deliverable plan that satisfies everything his physician requires. At this point he would normally have the physician review his plan and approve it. The planner has this degree of certainty at this point. The point of this program is to provide additional checking to ensure nothing has been overlooked by the planner before he presents the plan to the physician. The program changes nothing in his plan. It is just a reader of existing plan data and then evaluates it against a variety of criteria. The planner *should* have already done this process himself. The program merely double-checks everything (And adds additional checking that I believe should be done, but not necessarily all of my colleagues agree with me on this.). > Unambiguous function names and keyword-only parameters (not available in > Python 2) and of course tests help, but you might also consider custom types > that are restricted to a well-defined set of operations. A sketch: I do check the numbers and units both for falling within a proper range of allowed values and correct associated units for what is being measured. This happens at several places, but not every place where the information is is used. But data is checked as it enters the workflow and at multiple points during the program's workflow and finally at the end result. Since I am not writing classes yet I am not taking this approach yet. But I see a greater value in doing it this way as the information would be constantly checked for validity. > # For illustration purpose only! > class Percent: > def __init__(self, value): > if value < 1 or value > 100: # XXX allow 0%? > raise ValueError > self.value = value > def factor(self): > return self.value / 100.0 > def __repr__(self): > return "{} %".format(self.value) Something like this would have to be tweaked depending on what structure and what parameter is being evaluated. Actual dose to *something* in the patient can vary between 0% (For something receiving essentially no dose--far from the area of treatment.) to the value of point of maximum dose, which, for an SBRT-type plan, could be as high as 160% of prescription dose. Of course such high doses are only allowed to occur within the confines of the tumor being treated (NEVER outside of it!). [...] > target_dose.partial_dose(0.1) # raises TypeError > > Output: > > $ python gray.py > 20 Gy > 2.0 Gy > 2.0 Gy # 10 % of the target dose > Traceback (most recent call last): > File "gray.py", line 43, in > target_dose.partial_dose(0.1) # raises TypeError > File "gray.py", line 27, in partial_dose > raise TypeError > TypeError I generate an output very similar to this except I must get the error to show up in the planning system software. I rephrase the error message into language that the planner will understand that makes sense in the context of his plan. If it is an issue with his plan, he will know exactly what the issue is and how to address it. For errors that indicate an issue with my coding the planner would receive a message that states where within the program the error occurred, using language that will make sense to the planner, but also pinpoint exactly where the error was generated. And to contact me immediately with the issue. > OK, I got carried away a bit with my example, but you might get an idea > where I'm aiming at. The way I wrote it it is pretty clear that Percent(10) > denote 10 rather than 1000 %. Amen! > I can't spare you a last remark: Python may not be the right language to > make this bulletproof. Would you elaborate on this? I am sure I don't have the experience with programming and programming languages to truly understand your point. As I final note I want to emphasize that I am not writing a program to *create* a treatment plan. Nor am I writing a program that can *alter* an existing treatment plan. It is merely reading output from the treatment plan and evaluating that output against agreed upon best practice numbers. If this program never gets implemented it will change nothing in how plans are created and implemented. If it does get implemented, then the planner will do what he would have done anyway in the absence of the program. However, if the program flags something for his attention, then something will get noticed that might not have. I wish to emphasize that most of these *somethings* would not be actual errors
Re: [Tutor] How (not!) lengthy should functions be?
On Thu, Apr 16, 2015 at 4:03 PM, Alan Gauld wrote: > On 16/04/15 17:47, boB Stepp wrote: [...] > 2) I have seen varying recommendations as to number of lines of code > > Most of these come from the days when we worked on dumb terminals with 24 > line screens. Actual measurements has shown that function length (within > reason!) is not a major factor in comprehension or reliability. In COBOL or > C it is not unreasonable to have functions over 50 lines long, sometimes > over a hundred. But in Python that would be very unusual. So I'd treat the > advise to limit length to about 20 lines of executable code to still be > valid, if you exceed it treat it as a red flag to check that you really need > it to be that long. Would not your comments above apply to line length as well? If yes, why are we still wedded to a 79-80 character limit to lines when most people's monitors are quite expansive, to put it mildly? boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to print ALL contents of a scrolled Tkinter window?
On Fri, Apr 17, 2015 at 2:28 PM, Alan Gauld wrote: > On 17/04/15 14:26, boB Stepp wrote: >> >> Solaris 10, Python 2.4.4 >> [...] > That's why GUI printing generally uses an entirely different > technique to print things (see my earlier email). In essence > this requires you to separate the data content and format > from the GUI presentation. The printed presentation must be > prepared by you the programmer and output to the new display > context(a printer). This means you need to decide how to > handle page breaks, page width and orientation etc etc. I had started thinking along these lines, but realized that I possess a severe lack of knowledge as to the details of the printer does its *magic*. I used to know a bit about how dot-matrix printers (non-color) worked, but that has been a very long time ago... You mentioned groff in the other thread. Is this relatively easy to adapt to its formatting commands? Is it likely to be on my bare-bones Solaris 10 workstation? I will have to check to see what is present Monday. > Its a whole different ballgame and much more complex than > simply issuing a print command. Hard copy output from a > GUI is one of the hardest things to do in almost any GUI, > especially if you want it truly WYSIWYG. I am surprised that Python does not have a standard library module to help with this. I see that there are third-party modules, but that does not help me within my work environment constraints. > My personal favourite approach is to abandon WYSIWYG and > go for WYSRWYG - What you see resembles what you'll get... > And then I reformat the data using HTML, send it to a file > and print that file using whatever HTML rendering engine > I can find. Are there such HTML rendering engines likely to be present in a Solaris 10 environment, which is a rather bare-bones environment? I mean outside of a web browser. I can already use my existing template to auto-generate the appropriate HTML formatting (Once I write the needed functions to do so. But it should logically no different than how I interpret my template to render the Tkinter GUI display.), save that in a file and then? This would be needed to be done programmatically, not manually by the user. The desired end result is a pdf document to be stored electronically for posterity. > wxPython makes printing easier but even there its a > whole chapter(ch17) of the book and its at the end so > assumes you already know all the background around sizers, > device context and the like The example program - for > printing a formatted text document - runs to 2.5 pages of > code. And that's the easiest printing framework I've seen. Which book are you referencing here? Would it be "Wxpython in Action"? >> are along the lines of: 1) Determine how many rows of information >> appear in the viewing area. 2) Determine how many total rows of >> information exist to be printed. 3) Figure out how to programmatically >> do a *manual* scroll to bring up the hidden scrolled information. 4) >> Repeatedly apply the printing method. While I can probably make this >> approach work (It *seems* conceptually simple.), I cannot help but >> feel there is a much better way... > > > Its never going to be pretty but multiple screen captures > can work. Its certainly easy enough to reposition a scroll > bar programmatically from within a while loop. Figuring out > how many lines will depend on all sorts of things like > the size of fonts being used, how widgets are laid out. > That's what gets tricky, especially if users don't have > standardised screen sizes etc. I may or may not go this way. I already wrote a set of scripts (in shell and Perl) a few years ago to allow the user to click and drag an area of their screen to capture into a pdf document. It leverages the existing printer configurations and tools in the planning software. When the user is finishing making captures, he clicks the "Print to pdf" button and it converts the captures into a single pdf document, which it then ftps to the desired destination folder on a different portion of our intranet. This would provide a workable solution until I learn more. >> I intend to scour my available Tkinter documentation to see if there >> are root window level and scrolled area commands that might suggest >> another approach. > > > Not really. Tkinter (and Tk) basically sidesteps printing > to hard copy. There simply is no built in support. You have > to format it yourself. I did not find even a hint of anything beyond the already known Canvas widget postscript capability. > Check out IDLE - even it doesn't have any built in > formatted print. It only has 'Print Window', which is > just plain text. > Although even looking at how
Re: [Tutor] lists, name semantics
On Sat, Apr 18, 2015 at 3:28 PM, Bill Allen wrote: > On Apr 18, 2015 7:50 AM, "Peter Otten" <__pete...@web.de> wrote: > >> Bill Allen wrote: >> >> > Everyone that responded, >> > >> > Thanks very much for the excellent explanations! The distinction between >> > a reference to an object and a seperate copy of the object is quite clear >> > now. >> >> You can test your newfound knowledge by predicting the output of the >> following script: >> >> >> a = [1, ["x", "y"], 3] >> b = a[:] >> >> a[1][1] = "hello!" >> >> print(a) # [1, ['x', 'hello!'], 3] >> print(b) # what will that print? >> >> Think twice before you answer. What is copied, what is referenced? > print(b) will print the original copy of a which b now references which is > [1, ["x", "y"], 3] Uh, oh! You should have checked your work in the interpreter before replying! Peter is being very tricky!! (At least for me...) Look again at that list inside of a list and... boB P.S.: Watch out for top-posting. That tends to get peopled riled. I moved your response back into the normal flow of the interleaved conversation. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How (not!) lengthy should functions be?
On Sat, Apr 18, 2015 at 5:46 PM, Dave Angel wrote: > I'd still point out that eventually people will presumably get to believing > in your program. They'll subconsciously assume that if they mess up, the > program will notice, so they don't have to be as careful as they otherwise > would. Well understood! I have observed this in other things I have done that are being used, including the ancestor of this current project. I do not believe I have spoken much of it. It had been in use for approximately one year when I first discovered python and this mailing list. It is similarly a plan evaluation program, except it is used for the evaluation of our SBRT (stereotactic body radiation therapy) plans, whereas this project in development will be used -- at least initially-- to evaluate *normal* treatment plans. I think it has been in continuous use for going on four years now. It has never given an incorrect result. It has never failed its monthly constancy checks. It has rarely had a bug arise. When it has happened, it has been for something a user tried to do that I never imagined happening. But in each such instance (Keep fingers crossed, etc.) it has either crashed or displayed an error message describing the error, stopped program execution, and to contact me. The problem with this program is at the time of creating it, I knew its design was bad, but I did not have any options at the time. I needed the ability to display a graphical display of the plan analysis, but the only option our castrated work stations provided was to use the planning system's ability to create and display GUI elements. All of our workstations had Perl installed, but were missing dependencies (Which I was not allowed to correct.) to allow for GUI generation. I could have investigated the early versions of Java installed, but I wasn't prepared to go that route then. I tentatively looked into C/C++, but initial investigations revealed missing libraries, etc. there as well. So in the end I developed this hybrid of Perl code and planning system scripting language. You would not like the structure of the scripting language! I could go on quite a while, but I'll just mention that ALL variables are essentially both global and persistent. The variables and what they store do not go away until you exit the plan or purposefully destroy them. If I run one script, finish it and run a totally unrelated script it will have access to all variables and their last contents from the previous script unless the programmer explicitly destroyed those variables prior to that script's termination. Talk about potentially clashing namespaces! Because of these and other limitations that I had to work with, I was forced to have some program logic and substantial portions of the constraint data integrated with the GUI generation code. This led to maintenance hell the one time the constraint data had changed almost a couple of years ago. Steven's analogy of hammering nails with a paint brush comes to mind! But I got it to work and to work well. And this is much better than planners repeatedly doing by-hand calculations over and over and ... and over while they are trying to develop a viable plan. Which process is more likely to develop a patient critical error? Especially as the planner becomes fatigued under potentially heavy patient loads, where he must develop plans under time pressures? So I provided a solution that works. The planner uses it as a tool while developing his plans, undoubtedly *not* checking *any* of the calculations he used to do by hand. SUBSTANTIAL amounts of human labor are saved. When the planner feels he has a good plan, THEN he checks all of the program's calculations. If this is satisfactory, then he proceeds to getting the physician, etc. I believe that I come across on this list as much more ignorant and perhaps even much stupider than I actually am. This is because I am the sort of person who is unafraid to ask questions, no matter how trivial or how stupid I might make myself look by doing the asking. I would rather be absolutely certain that I understand what I am trying to do and the implications of what I am trying to do, then not ask due to potential embarrassment. At the very least, I want to identify the boundaries of my ignorance and incompetence. And after further pondering, if I feel I am still missing the boat on something, I'll have a go at asking again until I am satisfied with my comprehension. That is why I am so grateful to have access to your willing help and expertise! Anyway, back to the current project: The moment that they upgraded our systems, so that not only did I have full access to Python, no matter how old, but also that Tkinter was fully installed, was the moment I started designing a complete rewrite of the above-mentioned program. No matter how well working the program currently is, I *must* correct its major design flaws now that I have the tools available to do so. And I much prefer editing da
Re: [Tutor] lists, name semantics
On Sat, Apr 18, 2015 at 10:03 PM, Bill Allen wrote: > > On Apr 18, 2015 4:11 PM, "boB Stepp" wrote: >> >> On Sat, Apr 18, 2015 at 3:28 PM, Bill Allen wrote: >> > On Apr 18, 2015 7:50 AM, "Peter Otten" <__pete...@web.de> wrote: >> > >> >> Bill Allen wrote: [...] >> >> You can test your newfound knowledge by predicting the output of the >> >> following script: >> >> >> >> >> >> a = [1, ["x", "y"], 3] >> >> b = a[:] >> >> >> >> a[1][1] = "hello!" >> >> >> >> print(a) # [1, ['x', 'hello!'], 3] >> >> print(b) # what will that print? >> >> >> >> Think twice before you answer. What is copied, what is referenced? >> >> > print(b) will print the original copy of a which b now references which >> > is >> > [1, ["x", "y"], 3] >> >> Uh, oh! You should have checked your work in the interpreter before >> replying! Peter is being very tricky!! (At least for me...) Look again >> at that list inside of a list and... [...] > Ok, just tried it out. In this example b=a and b=a[:] seem to yield the > same results even after the change to a, which I do not understand. Should > not b be a copy of a and not reflect the change? Like you, I am on the path to learning Python, so I may or may not get all the technical details correct, but here goes (I'm certain that if I take any misstepps --pun intended!--that the ever-helpful crew of professionals will set us both straight): So far the emphasis on your original question has been on the differences between 'references to objects' and the actual 'objects'. I think that for the purpose of your question you can think about 'objects' as some sort of data stored someplace, though this is not technically correct. When an item of data is stored, it is more efficient to store it once and then from that point on use identifiers (Which we are used to thinking of in most instances as 'variables'.) to point to the storage location of that particular item of data. So when you originally said something like: my_list = ['a', 'b', 'c'] The ['a', 'b', 'c'] is the item of data stored and my_list is the identifier identifying *where* this particular item of data is stored. If you then do things like say: some_other_identifier = my_list then you just created a new identifier which gives the same location information to exactly the same piece of data. However, fortunately (Or, unfortunately, depending on your point of view.) you picked a type of data -- a list -- that is *mutable*. Like mutations in genetics, this just means that this item of data is capable of being changed in place, i.e., where it is actually stored in memory. So if Peter had said instead something like (Using the above statements.): some_other_identifier[1] = 'Hello!' I think you understand now that the originally *identified* list would now be ['a', 'Hello!', 'c'] . But Peter's actual example had a list inside of a list and BOTH of these are objects (In our discussion, items of data.) and BOTH of these have this property of being *mutable*. So he stuck an object inside of another object, so to speak. And this inner object has identifiers associated with it, too! Before Peter changed one of these changeable objects, he had: a = [1, ["x", "y"], 3] b = a[:] Now BOTH a[1] and b[1] now identify the location of the inner list object, ["x", "y"] . Apparently, Python, in its ever efficient memory management fashion, when it creates the new object/piece of data a[:], it sees no need to duplicate the inner list object, ["x", "y"], but instead creates another identifier/pointer/reference to this object's location. But since this inner list object is mutable, when you change "y" to "hello!" in b, you also change it in a because both a[1][1] and b[1][1] reference/point to the exact same storage location where this element of the inner list is actually stored. I hope this is helpful, and, if there are any misstepps, that when they are revealed both of our understandings will be enhanced! boB Stepp ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lists, name semantics
On Sat, Apr 18, 2015 at 11:08 PM, Cameron Simpson wrote: > Sometimes you want a "deep" copy, where "b" would have got a copy of the > iriginal x-y list. See the "copy" module's "deepcopy" function, which > supplies this for when it is needed: > > https://docs.python.org/3/library/copy.html#copy.deepcopy In this reference, part of it states: "Two problems often exist with deep copy operations that don’t exist with shallow copy operations: Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop. Because deep copy copies everything it may copy too much, e.g., administrative data structures that should be shared even between copies." If I am understanding things correctly, should not that last sentence read instead: "...structures that should *not* be shared even between copies." ??? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lists, name semantics
On Sun, Apr 19, 2015 at 12:24 AM, Cameron Simpson wrote: > On 19Apr2015 15:09, Cameron Simpson wrote: >> >> On 18Apr2015 23:26, boB Stepp wrote: >>> >>> On Sat, Apr 18, 2015 at 11:08 PM, Cameron Simpson wrote: [...] >>> "Two problems often exist with deep copy operations that don’t exist >>> with shallow copy operations: >>> >>> Recursive objects (compound objects that, directly or indirectly, >>> contain a reference to themselves) may cause a recursive loop. >>> Because deep copy copies everything it may copy too much, e.g., >>> administrative data structures that should be shared even between >>> copies." >>> >>> If I am understanding things correctly, should not that last sentence >>> read instead: >>> >>> "...structures that should *not* be shared even between copies." ??? >> >> >> No, the text is correct. > > > Um, my explaination was incomplete. [...] > The second sentence "Because deep copy copies everything it may copy too > much, e.g., administrative data structures that should be shared even > between copies" is an issuewhich is addressed lower down when mentioning the > __copy_ and __deepcopy__ methods. And it is not necessarily obvious. > > Suppose you've got a data structure of objects, which should broadly be > copied. However, _internally_, these objects may use some external > facility. Further, suppose that facility can't be copied; perhaps it is a > reference to a databse or something built around something like that. Like > this: > > G -> A >-> B >-> _open_database > > When you deepcopy that data sctructure you want to copy everything, but > _not_ copy the external facility object. So for the above example, after the > deepcopy you want this: > > Gcopy -> Acopy >-> Bcopy >-> _open_database > > i.e. the same reference to the database, but copies of "A" and "B". Ah! This example clarifies things for me. This provides a specific context for the phrase, "...that should be shared even between copies..." That now makes sense. > If you give "G"'s class a .__deepcopy__ method, then that will be called by > deepcopy() to make a copy of "G" by calling "G.__deepcopy__(memodict)". And > G's class will define its __deepcopy__ method to copy "A" and "B" but not > "_open_database". > > Most classes do not need this and deepcopy() just copies everything. > > Does this clarify things? Very much! Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lists, name semantics
On Sun, Apr 19, 2015 at 6:47 AM, Dave Angel wrote: > On 04/19/2015 12:07 AM, boB Stepp wrote: [...] >> I hope this is helpful, and, if there are any misstepps, that when >> they are revealed both of our understandings will be enhanced! >> > > Some of your knowledge of other languages is leaking into your explanation. > When we talk of the language Python, we need to distinguish between how > CPython happens to be implemented, how other Python implementations happen > to be created, and how C++ (for example) implements similar things. Some of > the above use pointers, some do not. The language Python does not. I actually was being deliberately *imprecise* in my use of technical terminology. But I see below that there are some nuances I need to learn... > So especially when talking of inner lists, we need to clarify a few things. > > An object has an identity, not a location. That identity can be checked > with the 'is' operator, or the id() function. But it exists all the time. But the object, in order to exist, must be stored in RAM somewhere, doesn't it? Or is the real point that we are adding an abstraction layer so we don't even have to think about where objects are physically stored in RAM? So I am the object referenced by "boB" and we don't care what my precise (x, y, z) coordinates are relative to the planet Earth. If we need to find me or modify me we use my label, "boB", to access me? > Variables, as you say, do not contain an object, they reference it. And the > formal term for that is binding. A name is bound to an object, to one > object, at a time. > > Now some objects have attributes, which is to say names, and those > attributes are bound to other objects. So if we define a class, and have an > instance of that class, and the instance has attributes, we can do something > like: > obj.inst_name > > and get the particular attribute. > > Still other objects have unnamed bindings. The canonical example is a list. > A list object has a bunch of bindings to other objects. Even though each > binding doesn't have a specific name, it nevertheless exists. And in this > case we use integers to specify which of those bindings we want to follow. > And we use a special syntax (the square bracket) to indicate which of these > we want. Ah, "unnamed bindings" was the concept I was talking around. I realized these were there and were referenced by the square bracket syntax, but I did not know what to call the concept. [...] > At this point, it should be clear what a shallow copy means. If the > original list's oneth item was a binding to another list object, *that* list > object does NOT get copied. > > I don't like the term "inner list", but I don't know if it's incorrect. > It's just misleading, since to the slice operation, the fact that it's a > list is irrelevant. It's just an object whose binding is to be copied. So the real point here is that there are two distinct copying mechanisms, deep and shallow. The "inner list" could just have been any other type of object, though if it had been an immutable type it would not have made Peter's original interesting point. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lists, name semantics
On Sun, Apr 19, 2015 at 4:05 PM, Dave Angel wrote: > On 04/19/2015 03:08 PM, boB Stepp wrote: >> >> Or is the real point that we are adding an abstraction >> layer so we don't even have to think about where objects are >> physically stored in RAM? > > > Somebody keeps track, but the address is not necessarily constant, and not > necessarily stored in any references. The references (bindings) are > abstract, and the details are unimportant to the user. For example, the > jython system does not use addresses at all. And an object gets moved > around from time to time without its references knowing it. The last sentence in this paragraph has me intrigued. Why would an object, once it has been created, be moved? What practical benefit does doing this give? boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] OT: Is there a good book that covers the history/evolution of software? [Inspired by the thread: lists, name semantics]
In the beginning (I assume.) there was machine code and only machine code. And I imagine this was not very good. Then I assume the next step was assembler, which probably only moderated the (then) tedium of coding. Then real high level languages were started to be developed, and this was very good. And then there were various new programming paradigms developed, and so on. What I am wondering is, is there a good book that covers in relatively good detail how we started at the most primitive level, machine code, and evolved to our current wonderful cornucopia of languages, operating systems, etc.? As the different threads reveal bits and pieces of the low level guts of Python, I am becoming more and more fascinated about how all of this is managed. Just the brief discussion of garbage collection details going on I find quite interesting. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to close a Tkinter window from a different thread?
I am not certain that my terminology is correct in the subject line. Let me explain my issue. Scenario A: 1) I start out inside a commercial software environment (Abbreviated CSA henceforth). 2) I initiate a script in the CSA's scripting language. 3) This script calls an external Python script.com 4) This Python script generates a Tkinter window, populating it with information from the CSA. 5) Control will not pass back to the CSA until the Tkinter window is closed. Because of this, none of the CSA's tools can be used until the Tkinter window is closed. Scenario B: 1) I start out inside the CSA. 2) I initiate a script in the CSA's scripting language. 3) This script calls an external Python script in a new thread. 4) This Python script generates a Tkinter window, populating it with information from the CSA. 5) Control returns to the CSA while the Tkinter window is populating itself. The CSA's tools can be used while the Tkinter window remains open displaying its information. My users want scenario B to occur. This way they can refer to the Tkinter window's info and make changes to their plan based on this info. However! Once they make their changes they will want to rerun the same Python script. This would then result in TWO Tkinter windows being open, one displaying the old info, the new one with the post-changes info. This is not acceptable. So, how do I: 1) Check for the existence of an already open window from a previous running of the script? 2) If such a window exists, how do I close it from the new script execution? And, then, of course generate a new instance of the information window. I need to be able to identify the existence of such a window without causing anything to happen to the CSA's normally open windows. And then close the particular window I need closed -- IF it is even open. I feel the solution must be in Tkinter's access to the X Window system, but nothing in the documentation is *clicking* with me yet. Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to close a Tkinter window from a different thread?
On Mon, Apr 20, 2015 at 2:10 AM, Alan Gauld wrote: > On 20/04/15 04:34, boB Stepp wrote: > >> So, how do I: >> 1) Check for the existence of an already open window from a previous >> running of the script? >> 2) If such a window exists, how do I close it from the new script >> execution? And, then, of course generate a new instance of the >> information window. > > > I would suggest forgetting about windows and think about > the processes that create them. Use the OS tools (via > the os module) to see if the first process is still running. > If so kill the process - which will in turn kill the window. I started poking around a little in this area in my books, but did not know if this was the way to go or not. I was still hung up on how to identify the correct process... > You can find the process based on its name or based on > its PID which you could store in a file somewhere > (like in /tmp?) I was thinking in these terms from a Tkinter window id perspective, but storing the PID while the original window is known to be open looks like the way to go. Thanks, Alan! I may have more questions on this later as I have not explicitly worked with this via Python. I've only killed processes via the command line before. >> I feel the solution must be in Tkinter's access to the X Window >> system, but nothing in the documentation is *clicking* with me yet. > > > Trying to manipulate GUIs via the windowing system should always > be a last resort, it is very hard to get right. If I am learning nothing else from my exploration of GUI programming, this is becoming ever more evident! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to close a Tkinter window from a different thread?
On Mon, Apr 20, 2015 at 2:10 AM, Alan Gauld wrote: > On 20/04/15 04:34, boB Stepp wrote: > >> So, how do I: >> 1) Check for the existence of an already open window from a previous >> running of the script? >> 2) If such a window exists, how do I close it from the new script >> execution? And, then, of course generate a new instance of the >> information window. > > > I would suggest forgetting about windows and think about > the processes that create them. Use the OS tools (via > the os module) to see if the first process is still running. > If so kill the process - which will in turn kill the window. > > You can find the process based on its name or based on > its PID which you could store in a file somewhere > (like in /tmp?) I'm currently at home and cannot access Solaris, but I believe that the following will do what I want: import os import signal from tkinter import * def kill(): os.kill(pid, signal.SIGKILL) root = Tk() pid = os.getpid() btn = Button(root, text='Kill me!!!', command=kill) btn.pack() root.mainloop() The process id would have to be stored persistently to do the real deal, of course, as Alan suggested. I cannot make this example work in Windows. As far as I can tell, signal.SIGKILL won't work with Windows. If I replace it with 9, then it does work. If I have understood what I have read to date, using signal.SIGKILL is preferable to using 9. Some questions: 1) Is the placement of "pid = os.getpid()" critical? My thinking is that I want to capture the pid of the root window, store it, and then use it if I need to kill the root and any children it has in my actual GUI display. If, say, I placed it immediately before "root.mainloop()", would it do what I want? Of course, I plan to experiment with this at work tomorrow. I'll also continue to play around with it in Windows. 2) The other possibility was to use "os.getppid" and, I suppose, "os.kill(ppid, signal.SIGKILL)". Would this be preferable? Or will wreak some sort of havoc? Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to close a Tkinter window from a different thread?
On Fri, Apr 24, 2015 at 8:41 AM, Steven D'Aprano wrote: > On Sun, Apr 19, 2015 at 10:34:43PM -0500, boB Stepp wrote: > >> Scenario B: >> 1) I start out inside the CSA. >> 2) I initiate a script in the CSA's scripting language. >> 3) This script calls an external Python script in a new thread. >> 4) This Python script generates a Tkinter window, populating it with >> information from the CSA. >> 5) Control returns to the CSA while the Tkinter window is populating >> itself. The CSA's tools can be used while the Tkinter window remains >> open displaying its information. > > I think one way of doing this is by making the Python script a daemon > that runs in the background. That at least will solve the problem from > Scenario A that the CSA becomes unresponsive while the Tkinter window is > open: as far as the CSA is concerned, the process it launched has ended. This part sounds promising. > Three follow-up problems then occur: > > - Can daemons run as graphical applications? > > - Once the daemon is running, how does the CSA communicate with it? I'd be extremely interested if this is possible! My biggest struggles are exchanging information between the CSA and other programs external to it. And it is much harder going in one direction than the other. Liberal use of temp files seems to be the most reliable means of exchanging information, though some exploitation of the CSA's global variables is possible, though this is usually a last ditch effort when nothing else seems to work. > - How do we make sure that the daemon closes down safely when the > CSA quits? > > > I don't know the answers to these. > > Ben Finney maintains a Python daemon library. If Ben is around, he may > be able to shed some further light onto this question, and answer > whether a daemon is suitable. Perhaps even give some sample code. I'll keep my fingers crossed! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Introductory questions on test-driven development and implementing Git version control.
I have just started reading "Test-Driven Development by Example" by Kent Beck during my lunch breaks at work. This book was a suggestion by Danny Yoo in another thread. So far it has been good reading. My current programming work flow is to add a little bit of code, run a *manual* test(s), inspect the results, correct anything that fails, rerun my manual test(s), etc. Frequently I run the entire program to see if anything has been damaged by the work so far. So TDD feels like it would fit very well with what I already try to do *manually*. I've known for a while that I need to move towards comprehensive automated testing, and I finally feel I know enough Python that I can focus on TDD and not be constantly struggling with Python syntax issues. And I really like this idea of writing a test first, it fails, now make the test pass, repeat. My wife (A teacher.) has been after me a lot lately to write some programs to make her teaching life better. So I would like to start one of her projects using TDD from the get-go. Also, this sounds like a good time to try to implement using version control software. While setting up Vim recently, I had to install Git (In order to get Vundle going.). So now I have that to play with. And to throw more fuel onto the fire of learning, why not jump into OOP for this project as well? It's about time! Plus it will make life with Tkinter a bit better, too. The project(s) will be coded in Python 3.4 on Windows 7 64-bit on my home computer. All projects that I actually complete for my wife will be implemented in her classroom, which has quite a variety of hardware and OS platforms: lap tops and desk tops, some of which are rather old, running Windows XP, Windows 7, and Ubuntu Linux. And possibly other combos that I have not been made aware of yet. First question: What testing modules/frameworks should I start out with? Doing a quick scan of the books I have, mention is made of doctest and unittest modules in the Python standard libraries. But mention is also made of two third party modules, nose and pytest. What would be the most productive use of my learning time while entering TDD waters for the first time? And beyond automating unit tests, how is integration testing done in an automated fashion? Will I require special software for this? And then there is user interface testing... And what would be the best approach to integrating Git with these efforts? Just how often does one commit one's code to the version control system? Or do I have some GCEs (Gross Conceptual Errors) here? Can Git be set up to automatically keep track of my code as I create and edit it? And as to automated testing: I really, ..., really would like to implement it on my side projects at work. But all such programs start in a proprietary scripting environment, which can call external Python (or other languages) scripts. The resulting final program is almost always an unavoidable amount of propriety scripting language (Which I always strive to minimize the amount of.), Solaris shell commands/scripts and Python. As I have been learning more Python and implementing it at work, I have found that the most successful approach seems to be to first get all of the information I need out of the CSA (commercial software environment) upfront, save it in temp files, then call a Python script to start the heavy duty processing, do everything possible in Python, generate a "reload" script file that contains language the CSA understands, and finally run that inside the CSA. How do I go about automating the testing of something like this? And apply TDD write tests first principles? And I would like to have all of that under version control, too. But while I am allowed to write my own programs for this CSA, I am not allowed to install anything else, strange as this may sound! Since the only functional editors in these bare-bones Solaris 10 environments are some simplistic default editor that I do not know the name of and vi, I long ago gravitated to doing my actual coding on my Windows PC (Being careful to save things with Unix line endings.) and FTPing to the environments where these programs will actually run. I AM allowed to install anything I want (within reason)on my PC. So I am thinking install and use Git there? And if successful automated testing can be done with this CSA situation, how difficult is it to backtrack and add test suites to stuff already written and being used? Are there special strategies and techniques for accomplishing such a feat? And any other suggestions to best start learning all of this as well as possible? As always, many thanks in advance! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.
On Fri, Apr 24, 2015 at 5:03 PM, Alan Gauld wrote: > On 24/04/15 20:09, boB Stepp wrote: >> >> allowed to install anything else, strange as this may sound! Since the >> only functional editors in these bare-bones Solaris 10 environments >> are some simplistic default editor that I do not know the name of and >> vi, > > > vi is a great editor, no major problems there, except it > doesn't have Python syntax awareness/coloring etc. I am quite happy with vi! I did not mean to imply otherwise. However, as you know I have only very recently started using Vim at home and don't consider myself productive in it yet. My game plan, is once I do, to start doing my editing at work directly in Solaris 10 on vi. > However from memory doesn't Solaris 10 come with a CDE GUI? > If so it should have a graphical editor in there someplace too. > It was a reasonable coding editor in that it did block indenting, > bracket matching, etc. Your memory is indeed correct as to CDE. It has a default graphical editor, the one I referred to as "simplistic", but if it has those features I have missed them. When I say "default", it is this editor that will pop up if I open a file for editing. I will look through the menus and help again. Maybe I gave it short shrift too soon! That does not mean that there is not another graphical editor in there somewhere. I will poke around some more. But it seems, Alan, that whenever I look for something that is *supposed* to be there, I find basically a stub of an application that is missing required libraries, etc. The installers of the planning software deliberately do NOT install a substantial amount of what would normally be there in any *normal* installation of Solaris. I once *begged* the support people for this planning system to install the missing stuff for Emacs, but they refused. Of course, this is after I found someone who even knew what Emacs was, but that is another story... But I may have to revisit all of this. We went to "Smart Enterprise" on this software about a year ago. I managed to abscond with one of the 810X boxes, with the planning software intact. I got my administration to let me keep it as my development and testing environment, since they do value the programs I generate (Whenever I get time to work on them, which is usually rare.). I think now that as long as I stay on this box, that no one will mind if I install anything. I just need not to do so on our Smart Enterprise clinical planning environment. I actually started to explore this route about a half-year or so ago, having figured out how to get the 810X connected to the Internet, but then I got distracted since by what they really pay me to do! > And of course it has the original SCCS for source control. > Which if there's only a few of you is adequate, and easy > to work with. I used SCCS on several major projects over > a 10 year period. There is just lil ol' me. I will have to research SCCS. >> And if successful automated testing can be done with this CSA >> situation, how difficult is it to backtrack and add test suites to >> stuff already written and being used? > > > That's the traditional way of doing testing! Its not that hard > if you can figure out a test environment. but from what I recall > this CSA is a GUI? That makes injecting messages/commands much > harder. There are tools that can do it but you can't install > them... It is a GUI. If I can initiate the testing process from within the CSA with a small script in its language AND have the testing software generate appropriate files in the CSA's language, then I can see how it all would work. But it sounds like I would have to write (and test) an interface program between the two. Of course I am just starting the path to learning TDD, so that will probably be at least a little ways off... > In your case building a usable test environment may be the > barrier, building the test is an evolutionary process that > shouldn't be too hard. I guess this is what I was thinking about just above... > If you have a CLI interface then file redirection makes > it relatively easy! If you can interact with its database > then stored procedures might provide away in. I do. But I don't see where you are going with this yet as I do not know enough about how these testing enviroments, etc. work yet. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.
On Fri, Apr 24, 2015 at 3:00 PM, Laura Creighton wrote: > In a message of Fri, 24 Apr 2015 14:09:45 -0500, boB Stepp writes: > You need the testing-in-python mailing list. Come on over ... > http://lists.idyll.org/listinfo/testing-in-python > You will find lots of familiar faces (email addresses) from this > list there. Nose and py.test are very similar. I happen to like > them better than unittest, but if you cannot install software on > your solaris machines, you may be better off with unittest which > comes with Python, which I assume you do have on your Solaris boxes. I have joined! The Python versions at work are 2.4.4 and 2.6.4(?)(Not certain about the last digit there.) Based on responses to date, the fact that unittest is in the standard library and that because of this most of my books have something about unittest, I will probably start there. I imagine that everything I learn with unittest will transfer over to other testing frameworks. >>And as to automated testing: I really, ..., really would like to >>implement it on my side projects at work. But all such programs start >>in a proprietary scripting environment, which can call external Python >>(or other languages) scripts. The resulting final program is almost >>always an unavoidable amount of propriety scripting language (Which I >>always strive to minimize the amount of.), Solaris shell >>commands/scripts and Python. As I have been learning more Python and >>implementing it at work, I have found that the most successful >>approach seems to be to first get all of the information I need out of >>the CSA (commercial software environment) upfront, save it in temp >>files, then call a Python script to start the heavy duty processing, >>do everything possible in Python, generate a "reload" script file that >>contains language the CSA understands, and finally run that inside the >>CSA. How do I go about automating the testing of something like this? >>And apply TDD write tests first principles? > > You need the testing-in-python mailing list. Whatever proprietary > thing you have to integrate with, chances are somebody there has > been there, and done that already and has code you would be > welcome to use. When I get farther along, I will probably have some very specific questions on this that I will post there. Steven and Alan have given me some very good feedback already! But if someone has already solved my problem, or, something very similar, then that will be great! >>And I would like to have all of that under version control, too. But >>while I am allowed to write my own programs for this CSA, I am not >>allowed to install anything else, strange as this may sound! Since the >>only functional editors in these bare-bones Solaris 10 environments >>are some simplistic default editor that I do not know the name of and >>vi, I long ago gravitated to doing my actual coding on my Windows PC >>(Being careful to save things with Unix line endings.) and FTPing to >>the environments where these programs will actually run. I AM allowed >>to install anything I want (within reason)on my PC. So I am thinking >>install and use Git there? > > Are you absolutely certain that you cannot install git on your bare-bones > Solaris 10 environments? Or plug in a memory stick and run code from > there? Because it would make your life so much easier ... I think that I can get an exception here (See a post in response that I made earlier today.). What I am *certain* of, is that I cannot install anything on our clinical planning environment. The Solaris workstation that I now have all to myself--I'm thinking they will now let me do what I want with it. But I must double check... But anything I develop there *should* work in the clinical environment. The planning software is the same though that may change soon as there are plans to go up a version and they may not want to do that on my testing/development machine. Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.
I saw something on Python-List that I think is worth getting on this list as Mark gave a very good reference... >Mark Lawrence wrote on Python-List: >>On 25/04/2015 01:51, Terry Reedy wrote: >>Based on my experience reading newbie posts on python list and >>Stackoverflow, learning to write real functions, without input and >>print, and repeatable tests, is the most important thing many people are >>not learning from programming books and classes. >Got to start them off somewhere so http://nedbatchelder.com/text/test0.html It is a talk that Ned Batchelder gave at PyCon 2014 called, "Getting Started Testing". You can watch the actual video (Which I just did.), go through the slides or read the slides with the video comments transcribed in. After watching the video, I feel I have a much greater understanding of testing and Python's tools to support it than I did a few minutes ago. I highly recommend watching this video -- Mr. Batchelder is a very good speaker and presents his material very effectively. Many thanks, Mark, for this link! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Questions (and initial responses) on using version control [Was: Introductory questions on test-driven development and implementing Git version control.]
N.B.: This is a manual recreation of portions of the original thread, "Introductory questions on test-driven development and implementing Git version control". The portions included here are those relevant to the version control. Where "[...]" appears, this indicates I did not include those portions of the original thread here. In a message of Fri, 24 Apr 2015 14:09:45 -0500, boB Stepp writes: [...] >My wife (A teacher.) has been after me a lot lately to write some >programs to make her teaching life better. So I would like to start >one of her projects using TDD from the get-go. Also, this sounds like >a good time to try to implement using version control software. While >setting up Vim recently, I had to install Git (In order to get Vundle >going.). So now I have that to play with. And to throw more fuel onto >the fire of learning, why not jump into OOP for this project as well? >It's about time! Plus it will make life with Tkinter a bit better, >too. >The project(s) will be coded in Python 3.4 on Windows 7 64-bit on my >home computer. All projects that I actually complete for my wife will >be implemented in her classroom, which has quite a variety of hardware >and OS platforms: lap tops and desk tops, some of which are rather >old, running Windows XP, Windows 7, and Ubuntu Linux. And possibly >other combos that I have not been made aware of yet. [...] >And what would be the best approach to integrating Git with these >efforts? Just how often does one commit one's code to the version >control system? Or do I have some GCEs (Gross Conceptual Errors) here? >Can Git be set up to automatically keep track of my code as I create >and edit it? [...] >And I would like to have all of that under version control, too. But >while I am allowed to write my own programs for this CSA, I am not >allowed to install anything else, strange as this may sound! Since the >only functional editors in these bare-bones Solaris 10 environments >are some simplistic default editor that I do not know the name of and >vi, I long ago gravitated to doing my actual coding on my Windows PC >(Being careful to save things with Unix line endings.) and FTPing to >the environments where these programs will actually run. I AM allowed >to install anything I want (within reason)on my PC. So I am thinking >install and use Git there? -- In a message of Fri, 24 Apr 2015 at 3:00 PM, Laura Creighton writes: >In a message of Fri, 24 Apr 2015 14:09:45 -0500, boB Stepp writes: [...] >>And what would be the best approach to integrating Git with these >>efforts? Just how often does one commit one's code to the version >>control system? Or do I have some GCEs (Gross Conceptual Errors) here? >>Can Git be set up to automatically keep track of my code as I create >>and edit it? >Depending on what you mean by that, the answer is 'no' or 'that is >exactly what git does, there is no way to _prevent_ this'. >You have to tell git when you would like to save your work. >It doesn't work like autosaving in an editor -- hah hah, she has typed >300 chars now, (or it has been 5 minutes now) time to autosave -- if >you never tell git to save the work, it will never get saved. >So what you typically do is write a test, tell git to save it, run the >test, have it fail, write some more code and run all the tests again, >have them pass, tell git to save it, write another test ... >If in the 'write some more code' part, you get the itch 'it would be >really bad if my laptop died and I lost all this work' you tell git to >save immediately and keep on going. >There is a whole other layer about 'how to share your code with other >people, politely, when several of you are working on the same project >at one time, but if you are a one man team, you won't have to worry >about that for a while. [...] >>And I would like to have all of that under version control, too. But >>while I am allowed to write my own programs for this CSA, I am not >>allowed to install anything else, strange as this may sound! Since the >>only functional editors in these bare-bones Solaris 10 environments >>are some simplistic default editor that I do not know the name of and >>vi, I long ago gravitated to doing my actual coding on my Windows PC >>(Being careful to save things with Unix line endings.) and FTPing to >>the environments where these programs will actually run. I AM allowed >>to install anything I want (within reason)on my PC. So I am thinking >>install and use Git there? >Are you absolutely certain that you cannot install git on your bare-bones >Solaris 10 environments? Or plug in a memor
Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.
On Sat, Apr 25, 2015 at 3:21 AM, Alan Gauld wrote: > Having looked at this thread and its early responses I think it > would be good to break it up into its two natural parts. TDD > and version control are pretty much separate concepts and > should be on separate threads. > > Bob, could you please ask your version control questions again, > taking account of early responses, on a new thread? That way > we can keep the TDD stuff together and the version control > stuff in a separate place. Done! I do not know if what I did matches your intent, but I hope so! I stuffed everything relevant to version control into a single email, trying my best to keep attributions, etc., accurate. It makes for a long post, but it has everything nicely in place. I just hope Gmail did not mangle anything! In retrospect, I wish I had copied and pasted every post so far into Vim, did my editing there, and re-copy and paste into a new email. I keep forgetting that text is text... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.
On Sat, Apr 25, 2015 at 3:20 AM, Laura Creighton wrote: > In a message of Fri, 24 Apr 2015 20:24:38 -0500, boB Stepp writes: >>The Python versions at work are 2.4.4 and 2.6.4(?)(Not certain about >>the last digit there.) Based on responses to date, the fact that >>unittest is in the standard library and that because of this most of >>my books have something about unittest, I will probably start there. I >>imagine that everything I learn with unittest will transfer over to >>other testing frameworks. > > What is even better, should you wake up one morning and decide that > you really want pytest, I written have a script that automatically converts > unittests to pytest tests. It is included with the pytest distribution. This is very good to know! >>> Are you absolutely certain that you cannot install git on your bare-bones >>> Solaris 10 environments? Or plug in a memory stick and run code from >>> there? Because it would make your life so much easier ... On your original post this did not register in my brain properly. This might be possible. The thin clients that hook us to Smart Enterprise *do* have a couple of USB ports. I know that they are functional as I watched the installer using one. I will have to investigate this! >>I think that I can get an exception here (See a post in response that >>I made earlier today.). What I am *certain* of, is that I cannot >>install anything on our clinical planning environment. The Solaris >>workstation that I now have all to myself--I'm thinking they will now >>let me do what I want with it. But I must double check... But anything >>I develop there *should* work in the clinical environment. The >>planning software is the same though that may change soon as there are >>plans to go up a version and they may not want to do that on my >>testing/development machine. > > This thought 'if it works here, it ought to work there' is an unworthy > thought for somebody who has learned to test their code. ;) You go to your > new machine. You pull down your tests and your code. You run all your > tests. When they pass, you don't just _think_ that the code _ought to_ > run here -- you _know_ the code will run because it passes all its tests. You have a very gentle way of chastising me! ~(:>)) I *do* test when I transfer code to the production environment, but to date these have all been manual. And the whole point here is for me to learn how to do full-fledged automated testing. And if there is ever a place to ensure I do this, it is in the production environment! But I did not see how to make it work there. Perhaps the memory stick idea or Alan's SCCS can get around these difficulties. > So we have got to find you a way that works to get your tests and a way > to run them on your production machines. > > Is there a way to stick a memory stick into these machines? Can you > mount a filesystem there and cd to it?... As I said above, I will see if this is doable. The ports exist, but are they usable? > ...So we keep all the code we care about on our memory > sticks, indeed in a virtualenv on our memory sticks. Solaris has > virtualenv -- I checked -- see > http://www.opencsw.org/packages/CSWpy-virtualenv/ I have only messed around with a virtual environment once a few years ago for some project at home that I no longer recall the details for. I did not get very deeply into understanding things, so I would have some learning curve here. On a different testing-related note, I have read that it is a good idea sometimes to do one's code testing within the confines of a virtual environment for safety reasons, particularly if some code comes from outside sources? Would you mind speaking to that topic? > So, right now, aside from a mandate from on high that people who > plug memory sticks into their computers shall be boiled in oil, or > the situation where your machines don't have any external ports at all, > I cannot see why this solution wouldn't work for you. There might be some who would enjoy doing this! ~(:>)) IS is a bit sensitive about the use of memory sticks. We have had multiple instances of virus infections via this route, often from people who really should have known better. But I am pleased to report I have not been one of them! (Keeping fingers crossed, knocking on wood, etc.) -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.
On Sat, Apr 25, 2015 at 10:58 AM, boB Stepp wrote: > On Sat, Apr 25, 2015 at 3:20 AM, Laura Creighton wrote: >> In a message of Fri, 24 Apr 2015 20:24:38 -0500, boB Stepp writes: >>>I think that I can get an exception here (See a post in response that >>>I made earlier today.). What I am *certain* of, is that I cannot >>>install anything on our clinical planning environment. The Solaris >>>workstation that I now have all to myself--I'm thinking they will now >>>let me do what I want with it. But I must double check... But anything >>>I develop there *should* work in the clinical environment. The >>>planning software is the same though that may change soon as there are >>>plans to go up a version and they may not want to do that on my >>>testing/development machine. >> >> This thought 'if it works here, it ought to work there' is an unworthy >> thought for somebody who has learned to test their code. ;) You go to your >> new machine. You pull down your tests and your code. You run all your >> tests. When they pass, you don't just _think_ that the code _ought to_ >> run here -- you _know_ the code will run because it passes all its tests. > > You have a very gentle way of chastising me! ~(:>)) While driving around doing chores today, I realized that I have been incredibly dense here! Of course I can carry my testing suites, etc., over to the production environment: This is will be all part of my code base, which I AM allowed to implement. Duh! If all Python standard libraries are installed on the two Python environments (2.4 and 2.6), then testing should not be an issue, other than taking the time to backtrack and get it going. Now VCS/DVCS programs is another matter entirely, but after hearing Laura's and Alan's input, one or both these solutions can surely be implemented. But is even this an issue? If I do my actual code writing on my Windows PC on which I AM allowed to install Git or whatever, and FTP the code to run to either the 810X or the production SE environments, then I will always have version control in place. I reread Steven's post tonight, and he actually answered affirmatively to this question; it just did not penetrate until this evening. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.
On Fri, Apr 24, 2015 at 7:36 PM, Steven D'Aprano wrote: > So many questions... let's hope I don't miss any... :-) > > On Fri, Apr 24, 2015 at 02:09:45PM -0500, boB Stepp wrote: > >> First question: What testing modules/frameworks should I start out >> with? Doing a quick scan of the books I have, mention is made of >> doctest and unittest modules in the Python standard libraries. But >> mention is also made of two third party modules, nose and pytest. > [...] > unittest is quite easy to use, and powerful. Some people complain that > it is not very Pythonic, but I've never felt that. It is also based on a > standard and much-copied Java library, so there are versions of unittest > for many different languages. I quite like it. I will definitely start out my learning by going this route. Will work at work (Though Monday I must do an actual import of unittest to ensure it is actually on both environments. Ya never know...) and also at home. >> And as to automated testing: I really, ..., really would like to >> implement it on my side projects at work. But all such programs start >> in a proprietary scripting environment, which can call external Python >> (or other languages) scripts. The resulting final program is almost >> always an unavoidable amount of propriety scripting language (Which I >> always strive to minimize the amount of.), Solaris shell >> commands/scripts and Python. As I have been learning more Python and >> implementing it at work, I have found that the most successful >> approach seems to be to first get all of the information I need out of >> the CSA (commercial software environment) upfront, save it in temp >> files, then call a Python script to start the heavy duty processing, >> do everything possible in Python, generate a "reload" script file that >> contains language the CSA understands, and finally run that inside the >> CSA. How do I go about automating the testing of something like this? >> And apply TDD write tests first principles? > > TDD principles apply to any programming language. So long as the > language that you use to write the tests has ways of calling your shell > scripts and CSA code, and seeing what results they get, you can test > them. CSA scripting can indeed call both its own scripts and external (to the CSA) ones. But everything must start within the CSA, or none of the CSA's scripts that are part of the overall program can be called. As far as I know, there is no way to initiate a CSA script from the outside, though just to double check I might post that question on the CSA's Google group. > However, I *religiously* write the documentation first. If I don't > document what the function does, how will I know what the code should > do or when I am finished? Every day I code this sinks more deeply into my bones... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Questions (and initial responses) on using version control [Was: Introductory questions on test-driven development and implementing Git version control.]
On Sat, Apr 25, 2015 at 10:30 AM, boB Stepp wrote: > On Fri, Apr 24, 2015 at 7:36 PM, Steven D'Aprano wrote: >>On Fri, Apr 24, 2015 at 02:09:45PM -0500, boB Stepp wrote: > > [...] > >>> And what would be the best approach to integrating Git with these >>> efforts? Just how often does one commit one's code to the version >>> control system? Or do I have some GCEs (Gross Conceptual Errors) here? >>> Can Git be set up to automatically keep track of my code as I create >>> and edit it? [...] >>The executive summary of how I use version control: > >>- work on bite-sized chunks of functionality >>- when the tests all pass, commit the work done >>- push changes to the master repo at least once per day > > >>The way I use version control on my own is that I have typically use a >>single branch. I rarely have to worry about contributions from others, >>so it's just my changes. Make sure that all the relevent files (source >>code, documentation, tests, images, etc.) are being tracked. Static >>files which never change, like reference materials, should not be. > >>Starting from a point where all the tests pass, I decide to work on a >>new feature, or fix a bug. A feature might be something as small as "fix >>the documentation for this function", but *not* as big as "control >>remote controlled space ship" -- in other words, a bite-sized chunk of >>work, not a full meal. I write some tests, and write the minimal amount >>of code code that makes those tests pass: > >>- write tests >>- save tests >>- write code >>- save code >>- run tests >>- fix bugs in tests >>- save tests >>- write some more code >>- save code >>- run tests again >>- write some more code >>- save code >>- run tests again > > >>etc. Once the tests pass, then I have a feature and/or bug fix, and I >>commit all the relevent changes to the VCS. hg automatically tracks >>files, git requires you to remind it every single time what files are >>being used, but either way, by the time I run `hg commit` or `git >>commit` I have a complete, and hopefully working, bite-sized chunk of >>code that has an obvious commit message: > >>"fix bug in spam function" >>"correct spelling errors in module docs" >>"rename function ham to spam" >>"change function eggs from using a list to a dict" >>"move class K into its own submodule" > >>etc. Notice that each change is small enough to encapsulate in a short >>description, but big enough that some of them may require multiple >>rounds of back-and-forth code-and-test before it works. > >>I run the tests even after seemingly innoculous changes to comments or >>docstrings, especially docstrings. Edits to a docstring may break your >>doctests, or even your code, if you accidentally break the quoting. > >>Then, when I am feeling satisfied that I've done a sufficiently large >>amount of work, I then push those changes to the master repo (if any). >>This allows me to work from various computers and still share the same >>code base. "Sufficiently large" may mean a single change, or a full >>day's work, or a whole lot of related changes that add up to one big >>change, whatever you prefer. But it shouldn't be less than once per day. Thanks for taking the time to share your workflow. It is very helpful for me. > [...] > >>> And I would like to have all of that under version control, too. But >>> while I am allowed to write my own programs for this CSA, I am not >>> allowed to install anything else, strange as this may sound! Since the >>> only functional editors in these bare-bones Solaris 10 environments >>> are some simplistic default editor that I do not know the name of and >>> vi, I long ago gravitated to doing my actual coding on my Windows PC >>> (Being careful to save things with Unix line endings.) and FTPing to >>> the environments where these programs will actually run. I AM allowed >>> to install anything I want (within reason)on my PC. So I am thinking >>> install and use Git there? > >>Yes. This is what I plan to do. I have started reading the free online book, "Pro Git--Everything You Need to Know About Git, 2nd ed., c2014, which is accessible via the Git website. I also watched the video about Git for 4-year olds. Long video, but it gave a good overview of the Git way of implementing things. Again, thanks! I think that after reading the first two chapters of the book, I will know more than enough to get started. In actuality, after watching the video last night, I could probably get going now. But I am an inveterate book reader... boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?
I now have Git installed on my Windows 7 PC at work. The files that I wish to put under Git version control exist on a Solaris 10 workstation. In the Git bash provided, I can ssh into the Solaris 10 machine. I also can the CuteFTP program on my Windows PC to move/copy/etc. files between the two machines. How can I put these Solaris files under version control under these circumstances? I thought I had conceptually seen how to accomplish this via ssh, but if it is doable, my limited knowledge of Git and ssh is insufficient to find the path of success. In order to at least start putting these files under version control, I have created a repository for these files on an intranet drive, used CuteFTP to copy them into the repository from Solaris, and cloned this repository to my Windows PC. My current workflow is very clunky indeed: 1) Bring up file(s) to edit in my Windows editor from my local project working directory. 2) Perform edits. 3) Save edits. 4) In Git bash stage these. 5) Either CuteFTP or scp from Git bash the changed files to Solaris. 6) Test files in Solaris. 7) Repeat. As needed do Git commits and pushes. This is better than what I had been doing. At least I *am* moving into the version control world. But how can I make this (hopefully, lots) better? BTW, I have Git working well at home. As an update I am working on learning how to use Python's unittest module at home. Once I am successful there, I will implement this at work: after the fact on existing projects and from the get-go on new ones. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?
On Wed, Apr 29, 2015 at 12:04 PM, Albert-Jan Roskam wrote: > > -- > On Wed, Apr 29, 2015 4:21 PM CEST boB Stepp wrote: > >>I now have Git installed on my Windows 7 PC at work. The files that I >>wish to put under Git version control exist on a Solaris 10 >>workstation. In the Git bash provided, I can ssh into the Solaris 10 >>machine. I also can the CuteFTP program on my Windows PC to >>move/copy/etc. files between the two machines. How can I put these >>Solaris files under version control under these circumstances? I >>thought I had conceptually seen how to accomplish this via ssh, but if >>it is doable, my limited knowledge of Git and ssh is insufficient to >>find the path of success. > > > ... (3) install git if needed ... It seems Git is needed, but I am not allowed to install it on the Solaris workstation. So is there a way around this? > > But uhhm, this is not Python at all ;-) I was hoping for clemency on this point due to the earlier thread(s) I started (Which included Python's unittest module.). -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?
Python 2.4.4, Solaris 10. I have some functions that I believe I could collapse into a single function if I only knew how: def choose_compare(operator, value0, value1, pass_color, fail_color): """ Perform the comparison indicated by operator. Return pass_color if true, fail_color if false. """ if operator == '<': return less_than(value0, value1, pass_color, fail_color) elif operator == '<=': return less_than_or_equal(value0, value1, pass_color, fail_color) elif operator == '=': return equal(value0, value1, pass_color, fail_color) elif operator == '>': return greater_than(value0, value1, pass_color, fail_color) elif operator == '>=': return greater_than_or_equal(value0, value1, pass_color, fail_color) else: print 'WarningMessage = "Invalid comparison operator in function, choose_compare().@Please contact script administrator for assistance.";' def less_than(value0, value1, pass_color, fail_color): """ See if value0 is less than value1. If true, return pass_color. If false, return fail_color. """ if value0 < value1: return pass_color, True else: return fail_color, False def less_than_or_equal(value0, value1, pass_color, fail_color): """ See if value0 is less than or equal to value1. If true, return pass_color. If false, return fail_color. """ if value0 <= value1: return pass_color, True else: return fail_color, False ... 3 more functions ... I won't give the remaining functions for the other comparison operators. The string variable, operator, is originally populated from a data file, which tells what type of comparison needs to be made. The last two functions I gave (and the ones I omitted giving) all follow the same exact pattern. I know there has to be some way to replace these 5 functions with 1, but what experimentation I have done to date has not worked. Also, what about the first function above? I could use 2 dictionaries, 1 for calling the 5 functions and one to pass the arguments, but is it worth doing this? Or, I would not be surprised if there is a much better way! ~(:>)) Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?
On Wed, Apr 29, 2015 at 3:46 PM, Marc Tompkins wrote: > On Wed, Apr 29, 2015 at 1:10 PM, boB Stepp wrote: >> >> Python 2.4.4, Solaris 10. >> >> I have some functions that I believe I could collapse into a single >> function if I only knew how: >> >> def choose_compare(operator, value0, value1, pass_color, fail_color): >> """ >> Perform the comparison indicated by operator. Return pass_color if >> true, fail_color if false. >> """ >> if operator == '<': >> return less_than(value0, value1, pass_color, fail_color) >> elif operator == '<=': >> return less_than_or_equal(value0, value1, pass_color, fail_color) >> elif operator == '=': >> return equal(value0, value1, pass_color, fail_color) >> elif operator == '>': >> return greater_than(value0, value1, pass_color, fail_color) >> elif operator == '>=': >> return greater_than_or_equal(value0, value1, pass_color, >> fail_color) >> else: >> print 'WarningMessage = "Invalid comparison operator in >> function, choose_compare().@Please contact script administrator for >> assistance.";' >> >> def less_than(value0, value1, pass_color, fail_color): >> """ >> See if value0 is less than value1. If true, return pass_color. If >> false, return fail_color. >> """ >> if value0 < value1: >> return pass_color, True >> else: >> return fail_color, False >> >> def less_than_or_equal(value0, value1, pass_color, fail_color): >> """ >> See if value0 is less than or equal to value1. If true, return >> pass_color. If false, return fail_color. >> """ >> if value0 <= value1: >> return pass_color, True >> else: >> return fail_color, False >> >> ... 3 more functions ... >> >> I won't give the remaining functions for the other comparison >> operators. The string variable, operator, is originally populated from >> a data file, which tells what type of comparison needs to be made. The >> last two functions I gave (and the ones I omitted giving) all follow >> the same exact pattern. I know there has to be some way to replace >> these 5 functions with 1, but what experimentation I have done to date >> has not worked. >> >> Also, what about the first function above? I could use 2 dictionaries, >> 1 for calling the 5 functions and one to pass the arguments, but is it >> worth doing this? Or, I would not be surprised if there is a much >> better way! ~(:>)) >> >> Thanks! > > > Here's what I came up with: > > def choose_compare(operator, value0, value1, pass_color, fail_color): > comps = {"=":"==", "<":"<", ">":">", "<=":"<=", ">=":">="} > if operator in comps.keys(): > operator = comps[operator] > if eval("{} {} {}".format(value0, operator, value1)): > return pass_color, True > else: > return fail_color, False > else: > print('WarningMessage') > > I would ordinarily avoid eval() like the plague, but I think that this > sanitizes the input pretty effectively. I had to make comps a dict instead > of a list because (in your example, anyway) you're using a single equals > sign to check for equality, which throws a Syntax Error (e.g. "if 1 = 2" > instead of "if 1 == 2"). I could deal with the "=" issue by either reformatting my data file to use "==" in place of "=", or when I parse the data file, do the replacement there. A list instead of the dictionary looks a little easier on my eyes. The list has me so leery of eval and exec that I totally forgot about this possibility! There are only two places in my program where I read information directly into my program: 1) The data file, or 2) how the user of the planning software names his regions of interest (ROI) in the planning system software. I will reexamine my checks of (1). For (2) the planning software already has its own checks, which would filter out a lot. And I am checking the ROIs to see if they are present in the data file *exactly* as given in the data file; otherwise, I reject them. So I have stumbled (With your gracious help!) into a legitimate use of eval()? Many thanks, again! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?
On Wed, Apr 29, 2015 at 3:50 PM, Laura Creighton wrote: > I forget. You are writing these things as functions rather than > methods of a class, because you don't know how to use classes yet? You forget nothing! ~(:>)) > Because you are absolutely correct that there are ways to simplify this, > but if you don't know how to use classes yet, put this on hold until > you do. And this particular thing you want to do is not the optimal > place to start learning about how to use classes. Since the unittest module creating test classes, I have commenced formal studying of this topic. But as you point out, not ready for it yet! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?
On Wed, Apr 29, 2015 at 9:40 PM, Cameron Simpson wrote: > On 29Apr2015 12:12, boB Stepp wrote: >>> >>> ... (3) install git if needed ... >> >> >> It seems Git is needed, but I am not allowed to install it on the >> Solaris workstation. So is there a way around this? > > > What do you mean by "install"? Bear in mind that while you may be forbidden > from installing git in the main areas (/usr, /usr/local, whatever), you may > be free to install it in your own home directory. It is just an > executable... On the smart enterprise where we (now) do our clinical planning they are very strict: no installing any external software; no accessing the Internet; no email; etc. Not all centers adhere to this level of strictness, but ours does. To be honest, I am surprised they allow me to do the programming I do, but so far it has been all pluses and no minuses, and for those dosimetrists who choose to use the tools I have developed, they are more productive than they would be doing things by hand. Now the 810X Solaris workstation that was retired when we went to smart enterprise is *mine* and they really don't care anymore what I do with it. When it was being used for actual clinical planning, it had its Internet access disabled, etc. I have since restored it, so I could install software now, including Git. But I am reluctant to do anything that I am not allowed to replicate on smart enterprise. I am trying to keep it as close to identical to the actual clinical environment as I can. Perhaps this is misguided on my part? As always, I welcome your thoughts. It could be I am being unnecessarily cautious in regards to the 810X, but as has been pointed out there is much I do not know, so my motto is to first ensure I do no harm... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?
On Wed, Apr 29, 2015 at 4:42 PM, Mark Lawrence wrote: > This isn't a job for Bicycle Repair Man!!! Not even if we only use the latest, greatest, computer-aided bicycle repair technology??? > ... It smacks to me of dictionaries > and the operator module but I'm too bone idle to look it up myself, so try > here https://docs.python.org/3/library/operator.html > D'oh :) So little time, so much Python standard library! I *do* search and search and ... search before I ask, but my Google-fu is often weak, especially when I am searching for hints as to how to solve a problem where I am unsure of the correct technical terminology to use in the search. OTH, I have sometimes spent hours searching, both online and in what books I have, and thus spared y'all many, ... , many other questions that I might have otherwise asked! One problem I have with searching the Python documentation is this: https://docs.python.org/release/2.4.4/lib/lib.html I never would have guessed beforehand that I would be needing to look under: "3. Python Runtime Services! I spend most of my time on this page as this is my most limiting version of Python that I must deal with. This page is *not* well-formatted and it all runs together. Even when I *know* something is there, I find myself having to Ctrl-F and entering the term I am looking for. And when I am not sure what I am looking for, I don't usually come up with the correct term. The later Python docs are much easier on the eyes, I do say! Anyway, Mark, thanks for the link! This looks quite straightforward and I will be able to side-step the evils of eval() once again. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?
On Wed, Apr 29, 2015 at 5:49 PM, Peter Otten <__pete...@web.de> wrote: > boB Stepp wrote: >> So I have stumbled (With your gracious help!) into a legitimate use of >> eval()? > > No. To expand on Marks hint here's how to do it without evil eval(). > > import operator > > comps = { > "=": operator.eq, > "<": operator.lt, > ">": operator.gt, > # ... > } > > def choose_compare(operator, value0, value1, pass_color, fail_color): > op = comps[operator] > if op(value0, value1): > return pass_color, True > else: > return fail_color, False > > print(choose_compare("=", 1, 1, "red", "blue")) > print(choose_compare("<", 1, 2, "red", "blue")) > print(choose_compare("<", 2, 1, "red", "blue")) > > Rule of thumb: when you think you need eval() you're wrong. Thanks, Peter! The lure of eval() once more avoided... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?
On Wed, Apr 29, 2015 at 10:39 PM, Cameron Simpson wrote: > On 29Apr2015 22:10, boB Stepp wrote: >> On the smart enterprise where we (now) do our clinical planning they >> are very strict: no installing any external software; no accessing the >> Internet; no email; etc. Not all centers adhere to this level of >> strictness, but ours does. [...] But I am reluctant to do >> anything that I am not allowed to replicate on smart enterprise. I am >> trying to keep it as close to identical to the actual clinical >> environment as I can. > > > And fair enough too. I frequently wish our developers' dev environments more > rigorously modelled the target environment. > >> Perhaps this is misguided on my part? > > > Not necessarily. > > But I would be inclined to distinguish your working tools from the target > environment. > > For example, I commend you making your dev environment as close to identical > to the actual clinical environment as you can. But I wouldn't deprive > yourself of tools that enhance your code management practices without > affecting that environment. > > For example, there is much to be said for tracking your changes with a tool > like git or hg. It encourages your to annotate your changes, and lets you > review history to see when and why some change occurred, especially if a new > bug has arisen. Distributed version control systems like git and hg also > make it easier to work on distinct changes to the same code as separate work > processes; of course the price for such a workflow is that you need to merge > the two things later and ensure that they do not interact badly. Totally, totally convinced of the correctness of this. Actively working to implement this. See below. > If you're serious about keeping the two environments very similar, you could > always do your _coding_ on a third platform (a laptop or whatever) using > your desired tools and _deploy_ the code to the dev (and later, prod) > environments from there, keeping the dev environment pristine. By "deploy", > that can be as simple as copying the code to the target. That is what I have implemented as of today. I installed Git on my Windows PC where I have been doing my actual coding anyway, created the needed repositories, including an extra one on our intranet in case my PC dies, etc. The current project is now in version control. After doing some editing and saving, I use the Git bash shell that came with Git and scp the file(s) to the dev environment, do my testing (Still manual; working on getting automated, but this will have more of a learning curve for me than using Git.), etc. When I get a meaningful chunk of something done, I add and commit in Git on the Windows PC. Less often I push to the intranet repo. Your comments suggest that I am on a reasonable track. The main danger as I see it is that if I am not careful, then the code on the dev environment could diverge from the state of code on my Windows PC, i.e., I forgot to do the scp part. But when I am actively working on a section of code I always insert a few print statements (Py 2.4!) to verify I am getting what I should when I test it out--even if I don't have an actual problem yet. And so far this has immediately revealed those few instances so far when I forgot to save to the dev machine (Usually when someone has interrupted my workflow, a near constant occurrence at work.). -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?
On Wed, Apr 29, 2015 at 11:38 PM, Dave Angel wrote: > On 04/30/2015 12:28 AM, boB Stepp wrote: >> >> The main danger as I see it is that if I am not careful, then the code >> on the dev environment could diverge from the state of code on my >> Windows PC, i.e., I forgot to do the scp part. But when I am actively >> working on a section of code I always insert a few print statements >> (Py 2.4!) to verify I am getting what I should when I test it >> out--even if I don't have an actual problem yet. And so far this has >> immediately revealed those few instances so far when I forgot to save >> to the dev machine (Usually when someone has interrupted my workflow, >> a near constant occurrence at work.). >> >> > > Add an automatic file copy to the save-key definition in your editor. Then > whenever you save the file locally, you'll also be copying it to the master > location. Many, many thanks, Dave! This was easily done in and will match my local and remote file saves exactly as they need to be. It did not even occur to me that this feature existed. Heavy, sigh! I have so many blind spots... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Ancient Python versions (was: Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?)
On Thu, Apr 30, 2015 at 12:15 AM, Ben Finney wrote: > boB Stepp writes: > >> One problem I have with searching the Python documentation is this: >> https://docs.python.org/release/2.4.4/lib/lib.html > > If you actually need to read the documentation specifically for a Python > version that has not been supported since 2008, then I agree that is a > problem. I'm pretty much stuck with these relics of Pythons past. > The documentation has improved since then. If you want newer-looking > documentation, maybe you should not expect it from a Python released > nearlt a decade ago? No, I am not looking for fancy aesthetics. I am looking for intelligent use of whitespace, so that everything does not run together into a nearly indistinguishable blob. Bold main section headings would be nice as well. All of this has been possible forever and evermore. Readability counts! ~(:>) -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Questions (and initial responses) on using version control: Why cannot I push my single (master) branch to origin without an error occurring?
I created my remote repository on, say my C-drive, with "git init". I then copied and pasted a file to that location and put it under version control with "git add filename.py". Next I went to my E-drive, which is where I intend to be my working directories. After setting up a similar directory structure (/Projects/), I typed "git clone C:/Projects/project_name" and the desired result appeared on E: E:/Projects/project_name/filename.py. All seemed well with the world! Now I made some edits to filename.py in my working directory, added/committed and then attempted to push to the remote repository and got this: boB Stepp@DREAMMACHINE1 /e/Projects/project_name (master) $ git push origin master Counting objects: 5, done. Delta compression using up to 8 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 328 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) remote: error: refusing to update checked out branch: refs/heads/master remote: error: By default, updating the current branch in a non-bare repository remote: error: is denied, because it will make the index and work tree inconsist ent remote: error: with what you pushed, and will require 'git reset --hard' to matc h remote: error: the work tree to HEAD. remote: error: remote: error: You can set 'receive.denyCurrentBranch' configuration variable to remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into remote: error: its current branch; however, this is not recommended unless you remote: error: arranged to update its work tree to match what you pushed in some remote: error: other way. remote: error: remote: error: To squelch this message and still keep the default behaviour, set remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'. To c:/Projects/project_name ! [remote rejected] master -> master (branch is currently checked out) error: failed to push some refs to 'c:/Projects/project_name' I did the usual Google search. What I found recommended I cd to the remote repository, create a new temporary branch, and then checkout that branch. Then go back to my working directory and then push to the remote repository. This works. Problem: I don't understand why what I was originally doing does not allow me to do a push with errors. Would someone please elucidate? And since I am obviously not in the know here, my attempted workflow must be flawed. Would someone point out the "proper" way to initiate a new project under Git version control? Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.4 (was comparison operators)
On Thu, Apr 30, 2015 at 1:02 AM, Laura Creighton wrote: > Python 2.4 is really old, right now. OpenCSW has 2.6.9 > http://www.opencsw.org/package/python/ > > Any chance you could use that? Laura, I may just attempt this on the dev machine. I have mentioned before that the production environment is running Python 2.6.x (I think it is 2.6.6, but don't remember for certain.). Surely updating Python on the dev to one very near the prod env is an improvement? And if I am going to do that, I might as well install Git. And I will probably throw in gVim, too. I have been pondering everyone's comments to date, and it seems to me that I should be doing all of my development on the development environment machine and it is thus justifiable to add the tools I need to effectively do this (Again, thanks for your thoughts, Cameron!). This seems more *sane*! Plus it will save me tons of time. Even though the link you gave was for a package add, I just *know* there will be missing dependencies. Guess I will have to learn how to resolve all the issues that come up. Should be fun! Thanks, Laura! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Questions (and initial responses) on using version control: Why cannot I push my single (master) branch to origin without an error occurring?
On Thu, Apr 30, 2015 at 11:21 PM, Alex Kleider wrote: > On 2015-04-30 20:39, boB Stepp wrote: >> >> I created my remote repository on, say my C-drive, with "git init". I >> then copied and pasted a file to that location and put it under >> version control with "git add filename.py". Next I went to my E-drive, >> which is where I intend to be my working directories. After setting up >> a similar directory structure (/Projects/), I typed "git clone >> C:/Projects/project_name" and the desired result appeared on E: >> E:/Projects/project_name/filename.py. All seemed well with the world! >> >> Now I made some edits to filename.py in my working directory, >> added/committed and then attempted to push to the remote repository >> and got this: > > > I would suggest the following work flow to set up two parallel repositories: > > cd > git init > > git add > git commit > > cd > git clone > # the above command brings in a copy of all that was committed in the first > repo. > > Once this is done, I believe your subsequent commits can be pushed without > the errors. > https://mail.python.org/mailman/listinfo/tutor But this is what I did, and I got the pasted error. Is there some difference between what you are saying and what I posted that I am not picking up on? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Questions (and initial responses) on using version control: Why cannot I push my single (master) branch to origin without an error occurring?
On Fri, May 1, 2015 at 1:41 PM, Albert-Jan Roskam wrote: > > > On Fri, May 1, 2015 5:39 AM CEST boB Stepp wrote: > >>I created my remote repository on, say my C-drive, with "git init". > > Not with 'git init --bare'? Should I have used the option --bare? I was following along with the book, "Pro Git", which is available free on-line via the Git website. > I usually prefer initializing a remote with a readme, so I can simply clone > it and then populate it with files. No 'git init' and 'git remote add' needed. I'm not certain I am following you here. When you say you are "initializing a remote with a readme", have you first run "git init" or "git init --bare" in that directory? And I presume the readme is the typical readme file that most projects have? And then you go to your working directory and run your git clone command? And then as you generate files in your working directory, you push them to the remote? > This book is good: https://pragprog.com/book/pg_git/pragmatic-guide-to-git > Thanks for the link. Just now ordered it. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Questions (and initial responses) on using version control: Why cannot I push my single (master) branch to origin without an error occurring?
On Sat, May 2, 2015 at 3:15 AM, Albert-Jan Roskam wrote: > Check out this page: > http://stackoverflow.com/questions/7861184/what-is-the-difference-between-git-init-and-git-init-bare > > Isn't the error you mentioned before the same? After reading everything on the page you link to, plus the little bit on Git in "Introducing Python" by Bill Lubanovic, I think I understand what is going on a bit better. My current understanding is this: The workflow that I originally did resulted in TWO working directories being created with the same branch name, master; one where I meant the remote repository to be and one where I really meant for my work to be done. The error message reflects that Git will not allow both working directories to be working on the same branch at the same time, as Git has to allow for others wanting to access the repository and the branch master. Thus when I created a new branch on the repository and checked it out, there was now only one working directory actively developing the master branch, *not* at the repository's location. The repository's working directory was then set to have the new branch developed. Of course this was a throw away branch, to allow me to push to the repository from my *real* working directory. I don't know if I am saying this particularly well as I am still wrapping my mind around how Git structures things. I could have done one of two things: 1) Created a repository using "git init", and have my working directory there. In this instance, there would be no need for push or pull commands. Or, 2) Created a bare repository. This would result in there being NO working directory in that location. Go to my desired working directory location and type "git init". Create files, edit them, etc., adding/committing them there. When I am ready to push, I can push to the remote "bare" repository. No error messages result as no working directories exist on its location. My intent in having my work stored on two different hard drives, was to cover myself if one hard drive failed. So I tested arrangement (2) tonight. After generating some test files and pushing them to the remote directory, I grew concerned when I did not see any of the files I pushed there! But I followed through and deleted everything off of my working directory hard drive to simulate it crashing. While still there I typed "git clone remote_repo_location" and voila! My files returned!! I don't totally understand everything yet, but it makes a lot more sense now. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Learn python - Step by Step
On Sat, May 9, 2015 at 3:23 AM, acolta wrote: > > Hi guys, > > I want to start coding in python. My background is Linux/Bash/Perl > (begginner). > My appreciate if somebody will recommend books/tutorials + exercises to > practice. This question comes up quite frequently. If you have not done so already, try searching the Tutor archives. If you have a good bookstore nearby that is likely to carry programming-related books, you might just want to do some browsing and then look at reviews online. My local Barnes & Noble (I'm in the USA.) always has a selection of Python books. And of course there are tons of online resources, including tutorials on Python's official site. As always, a search engine is your good friend. Also, Alan Gauld (Moderator for this list.) has a good one. Look for one of his emails; he always has a link to it in his signature area. I am learning myself, and, being old-fashioned (I suppose.), I tend to prefer hard-copy books. If you feel any degree of comfort writing Perl scripts and programming in general, then you might jump into something like Mark Summerfield's two book series, "Programming in Python 3, 2nd ed." and "Python in Practice". If you want to go really deep and cover pretty much everything, then Mark Lutz has two quite thick books, "Learning Python, 5th ed." and "Programming Program, 4th ed." One nice thing about the latter two books (Besides their completeness of language coverage.) is that Lutz points out the differences between Python 2 and 3 implementations, where appropriate. But if you are really a beginner beginner and did not make it very far in writing sophisticated Perl scripts, then you might enjoy something like "Python Programming for the Absolute Beginner, 3rd ed." by Michael Dawson and "More Python Programming for the Absolute Beginner" by Jonathan S. Harbour. They both try to hold your interest and make things fun by designing only game-related programs. They both eventually use a form of the pygame module to get into graphics and audio. And for the stuff you already understand you can quickly skim through those portions. Finally, there are very knowledgeable people here willing to help you, but make certain you post your questions in a way that makes it easy for them to offer their help. Their time is very valuable and their efforts are entirely voluntary. So if you have not, please read the auto-generated email that covers how to post questions to this list, things like: Use plain text emails only; no top-posting (If you don't know what that means, search for it.); give your operating system and version of Python; think carefully about your question(s) and trim your code down to something that is self-contained and shows the exact problem you are experiencing; and, always post the *full* error report Python generates. HTH, -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to close a Tkinter window from a different thread?
Python 2.4.4, Solaris 10 I realize that this is a bit old, but I got severely sidetracked! ~(:>) On Mon, Apr 20, 2015 at 2:10 AM, Alan Gauld wrote: > I would suggest forgetting about windows and think about > the processes that create them. Use the OS tools (via > the os module) to see if the first process is still running. > If so kill the process - which will in turn kill the window. Is this a reasonable way to determine if a given pid is still active? I found this at: http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid import os def check_pid(pid): """ Check For the existence of a unix pid. """ try: os.kill(pid, 0) except OSError: return False else: return True I realize that this will also return True if I don't have permissions to kill, or some such. > You can find the process based on its name or based on > its PID which you could store in a file somewhere > (like in /tmp?) I can implement this, but thinking about this anew has led to a concern. Hypothetically, if I check for the existence of a running process based on this stored pid, what is the likelihood that the pid will be reassigned to something other than one of my program's windows left open? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Should error checking be duplicated for both functions if one function calls another one?
Suppose in a given state of a program, function 1 calls function 2. Function 1 includes checks for possible error conditions. If there are no issues, then function 2 should execute with no issues as well. The question is, should function 2 include the error checking done in function 1 if function 2 is only ever called by function 1? My inclination is to say yes, as in some future incarnation of the program function 2 might get called in new ways. What are your thoughts? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Should error checking be duplicated for both functions if one function calls another one?
On Mon, Jun 1, 2015 at 9:33 AM, David Palao wrote: > Hello, > Not sure if I got it, but, in my opinion functions should do only one > thing.So if function 2 finds an error, it should raise it. There > should be another function (function 1 in your case?) taking care of > possible raised errors. I guess my question was not clearly worded. The idea is that function 1 calls another function. Function 1 checks for possible errors that are relevant. Some or all of these checks are also relevant to the called function. Should the called function also include these relevant error checks? boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to use tkinter with a touch screen device?
Apparently I will be finding myself having to write some programs to run on a Samsung Slate tablet, manufactured circa 2011. It has Windows 7 home edition 64-bit as its OS. Hopefully Python 3 will be easily installed, and I will be able to run Python 3 programs on it. Operating under this assumption, what adjustments will I need to make in order to use tkinter for GUIs on this device? So far my searches have not found targeted information (yet). One thing I did find is that complex gestures are not supported by tkinter. But will tkinter see: 1) Short presses as a left mouse click? 2) Long presses as a right mouse click? 3) Virtual keyboard events the same as physical keyboard events? 4) Etc. ? Any useful info along these lines will be greatly appreciated! Otherwise, I will do the usual once I get this tablet updated and Python installed: Barge ahead, write some code, and see what happens! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use tkinter with a touch screen device?
On Fri, Jul 17, 2015 at 5:32 PM, Mark Lawrence wrote: > A possible starter > http://sumerulabs.in/blog/2015/02/21/touch-screen-for-the-new-raspberry-pi-2-available-in-india-sumerulabs/ > ??? I had briefly glanced at that, but other than a short snippet of code, it seemed to be more an advertisement for a new touch screen monitor for Raspberry Pi. In fact most of the search results I got earlier involve the Raspberry Pi. Nothing leaped out at me. I may have to sift through those results more carefully if nothing else turns up. But thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Design question: Web-based vs. desktop-based vs. desktop-based with data backed up to web server with a tablet thrown in for all cases?
My wife (a Montessori teacher of 7th through 9th grades) is trying to coerce me to create some helpful software for her classroom. She has lots of things she *wants*: Some involve only her and her record keeping. Some will involve both her and students. Some would additionally involve parents. With the parents it would have to be web-based. For students, some software would be used only in their classroom. Others would be used both in and outside the classroom. In my wife's case, she would want to be able to access the software and its data either at school or at home. Currently she does most of her work on a laptop that she carries back and forth between home and school. Anything involving student records would have to be kept secure. For her most urgent project to be done before school starts in 5 weeks (!), she wants me to enable her to assess her students' work as she wanders about the classroom using this Samsung Slate tablet the school has given her to use. This device would be okay for stuff like checking check boxes, navigating menus, radio buttons, drop-down list boxes, etc., but would be horrible for any type of manual data entry. So she would need to do the latter at her laptop, though she might do limited data entry on the tablet. I do own server space and a domain name that I have never used, but should be adequate for my wife's needs. The school has a wireless network that allows Internet access, which is usually (but not always!) reliable. The main question: How do I best handle the storage and access of my wife's classroom data in these three different scenarios (wife's access only; wife and student's access; wife's, student's and parent's), and have each party to have access to relevant software I create? Using this *most urgent* project as a starting example, this student assessment software would involve only my wife, the tablet and her laptop. Both the laptop and the tablet would have to both be able to run the software and have synchronized data between the two devices. If the student data resided only on these two devices, then protecting the student data isn't as much of an issue as long as my wife controls her physical devices. However, if the data were to reside on a server then that would become a more important issue. It would obviously be very important that data cannot be lost. I can easily imagine my wife dropping and destroying the tablet, the tablet's hard drive crashing, the laptop's crashing, etc. If the data were stored online, then possible school wireless network outages would be a potential bad problem. My best thoughts at the moment are to: 1) Find a way to always keep the laptop and tablet synchronized. 2) Have both devices write a backup copy of the data to the server whenever a change in the data occurs. 3) In case of wireless network failure, the software would realize this and know that whenever connectivity is restored to write any data that has changed in the interim. 4) The backup data on the server would have to be securely encrypted against whatever hackers might try to to access or intercept the data. (Hmm. What about the communications between the laptop and the tablet?) Is this a sensible way of approaching at least this one project? Of course, I have not a clue as to how to do any of this (yet!). As always, many thanks in advance! P.S.: My wife has researched existing software and has found everything lacking. She wants custom solutions to her custom needs. Oh, joy. But very interesting! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use tkinter with a touch screen device?
On Fri, Jul 17, 2015 at 10:13 PM, Laura Creighton wrote: > The place to ask this question is > https://mail.python.org/mailman/listinfo/tkinter-discuss but I think you are > out of luck... This would explain why I am having trouble finding much information. I *think* I could get things to work on the tablet if I restrict myself to coding for short press and long press gestures, and the virtual keyboard. But even this might be more involved than I would like. I read something a bit ago that one fellow could not get a short or long press gesture to work unless he coded for BOTH the press and release the press events. Not exactly analogous to a mouse-click event. > ... On the other hand, kivy > ought to work for you. http://kivy.org/#home I've yet to try it on > a windows tablet, though. I think it was you who mentioned this GUI framework on the main python list fairly recently. In fact, on my phone I have left its web page up to look at when I get a chance. Does kivy have all of the functionality of tkinter in addition to supporting multi-touch gestures? Any downsides I should be aware of? Judging by their "Hello, world" example, the code looks even simpler than tkinter. Does everything have to be written as classes? Thanks, Laura! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design question: Web-based vs. desktop-based vs. desktop-based with data backed up to web server with a tablet thrown in for all cases?
On Fri, Jul 17, 2015 at 11:18 PM, Laura Creighton wrote: > I have a plug in usb keyboard that I can just plug into my tablet. > It works great for data entry... I suggested this to my wife and believe she is looking into it. However, whenever she is walking about her classroom, she does not want to be messing with her keyboard, just quickly tapping and selecting predetermined skill assessment options (Student just beginning to learn; practicing now; has achieved mastery of this skill; etc.). > >>1) Find a way to always keep the laptop and tablet synchronized. > > All the cloud storage services want to sell you something that > does this. So does Dropbox. My wife has a Dropbox account and mentioned this as a possibility. >>Is this a sensible way of approaching at least this one project? Of >>course, I have not a clue as to how to do any of this (yet!). [snip] > The idea is to use as much off the shelf technology to do what you > want, and not reinvent the wheel. Especially when it comes to > security issues that, worse case scenario, have all the parents > suing you for not keeping things that are required to be private > from being hacked. > > Before there was cloud computing, and smartphones, we wrote a client > server app that handled the billing situation for the local energy > company -- plus all their power outages, service apps etc, etc, etc. > It took 4 of us nearly a year to get the permissions down right for > all possible cases. > > Doing the same sort of thing for our mobile app using existing > cloud libraries took about 3 weeks. Only some of that speedup was > due to the fact that we knew what we were doing a lot better the > second time around, and we had really extensive unit tests from > the old way of doingf that we could slightly refactor and then > make sure they passed under trhe new regime. > > You haven't picked yourself an easy one here ... Tell me about it! Vonda (my honored spouse) has been hinting about all of this for quite some time. But she had not figured out her exact needs. She actually still hasn't, but has a broad idea of what she initially would like to have now. And she has a greatly exaggerated idea of what I can accomplish in five weeks! I suspect version 0.0.1 will be something along the lines of: Everything basically exists on the tablet. Get a keyboard that works with the tablet. Manually backup/sync tablet with laptop as needed. Does the program have the basic functionality you *really* want as you wander about the room? Probably not. Tell me what you now need. Etc. Only when I feel I have what she really wants nailed down will I get into the rest of our discussion. But I *do* want to design my code with where the final version needs to go, so hopefully I won't have any major rewrites in my future! > One warning -- the trick to high speed performance for such things is > to copy as little data as is needed from one device to another (and > then let the devices regenerate a lot of what they need from the > basic necessary set). But the trick for _developing_ and > debugging such things is to send more information, including a > bunch of handshaking things like 'I am trying to open the MongoDB > Database now. Ok, that worked, now I am adding new job tickets ... > and so on and so forth. > > If you do not do things like that, the time will come when you sit > pointing at your server saying 'You aren't doing anything. Why aren't > you doing ?" Utterly frustrating. > YOu need to build a verbose way into what you do so you can have your > server tell you what it thinks it ought to be doing, and then a > way to shut the server up when you go into production. This makes a lot of sense! Must remember... > But I would go google for cloud services that have data synchronisation. > (Which is pretty much all of them, that being the point, after all). > You want to build your app out of some of these ready made parts, or > risk that your wife's students will all be in university before you are > done with your app. For sure! Especially when I get into some student drills programs that she will undoubtedly want the students to work on both in class and at home with an option for the parents to view their child's progress online. But for this student assessment project, it is going to have to be without all the desired bells and whistles to have something that will be practically useful for her when school starts. Especially when I am certain Vonda is still figuring out what she *really* needs! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design question: Web-based vs. desktop-based vs. desktop-based with data backed up to web server with a tablet thrown in for all cases?
On Sat, Jul 18, 2015 at 4:58 PM, Brandon McCaig wrote: > Rather than worrying about technology, frameworks, peripherals, > and protocols you need to focus on the real problem. Have her > describe exactly what she'll do with it. Try to get her to put it > into context of what she does NOW without the software so that > you can compare. I'm 29 years old so I've been away from school > for a long time. I don't know what teachers are using computers > for these days, but I cannot imagine it being useful to walk > around the classroom with a tablet (if anything I don't think I'd > want my children's teachers having such a distraction). At least, > not so useful as to commission the development of custom > software. I'm also not familiar with what a Montessori teacher > does, but it sounds even less likely that custom software will be > useful since it sounds like the students' learning is much less > organized than in a traditional school. The Montessori philosophy of teaching is quite non-traditional. Two or more different grades of children are taught in the same classroom, usually with just one teacher, who may or may not have any helpers. My wife often does not have help, or, if she does, it has not been as helpful as it might. She has 7th, 8th and 9th graders in her class. This coming school year she will have approximately 20 students. At any moment during the school day, all of the students are NOT doing the same thing. Some may be working in small groups. Others will be doing individual work, where it is quite likely that none of these students are doing the same assignment. Each student often has an individualized learning plan. The initial assessment project is quite needful. In the past my wife has wandered about the classroom assessing her students with either a clipboard in hand or trusting her memory until she got back to her desk and able to write down her assessment notes for each student. Note that students do not get traditional grades. Instead, they have a detailed list of skills that they are working towards mastery in. Her assessments will notate each student's progress towards mastery in light of whatever assignments they might be working on. When it comes time to interact with each student's parents, my wife needs to combine all of this assessment data into a report of the student's progress in each skill area to share with the parents. This is quite burdensome to do entirely by hand. The Montessori method of teaching is most frequently associated with children of age three up through sixth grade. There are relatively few examples of junior high/high school Montessori programs and there does not seem to be a good consensus of how to apply the Montessori methods to secondary education. So the main reasons why my wife does not have detailed requirements for what she would like me to program is that she has been working out what is and is not appropriate on her own. After several years of developing her program, she feels she is at the point where software can be a real help for her. BTW, she is very computer literate. She has done programming before when she was a university student and sporadically since then. So she is well aware of what is possible and what can be useful. I have not given you a good idea of what a Montessori education is all about. If you are curious I encourage you to do the usual online searching. In this thread, I kept it very general on purpose. I was probing this community for their thoughts on two things: 1) Should I make the software web-based or desktop-based? 2) What would be the best way of handling the data involved, particularly the data that impinges on student privacy concerns. As I said in the initial thread, some software would be strictly for the teacher's use. Some would be used by the students and the teacher with the potential that the students might have to access that software in their homes (homework). And finally in addition to the students and teachers, some things might be desirable for the parents to be able to monitor their student's progress from home. And then to make things at least a little more concrete I gave a very broad outline of the first project that she (perhaps foolishly ~(: >) ) hopes to have at the start of her school year. And I have been given some great thoughts by this community to help me on my way! I understand and appreciate your concerns. If the client was anyone but my wife, I would not be attempting this for all of the excellent reasons you gave. But Vonda is kinda the lone ranger here in what she is trying to build, and I think I can give her some real help. And from my perspective it is another opportunity to learn many cool new things and push my limits. I never seem to ever find time to just read and study a Python (or other programming-related) book from beginning to end, but when I have a concrete project to do, then at least I start learning *something* out of sheer necess
Re: [Tutor] Design question: Web-based vs. desktop-based vs. desktop-based with data backed up to web server with a tablet thrown in for all cases?
On Sun, Jul 19, 2015 at 5:28 PM, Laura Creighton wrote: > In a message of Sun, 19 Jul 2015 18:11:36 -0400, Dave P writes: >>On Jul 19, 2015 5:43 AM, "Laura Creighton" wrote: >>> >>> In a message of Sun, 19 Jul 2015 16:27:13 +1000, "Steven D'Aprano" writes: >>> >I'm not sure if it runs on Macs, but it should work on Android, Windows, >>> >and Linux, and of course it is entire Python-based. >>> >>> Python 2.7 only on for MacOSX. Python 3 is coming very soon. >>> >>> Laura >> >>Hi all, >> >>I can't help thinking we're trying to reinvent the wheel here. I would be >>quite surprised if Trello couldn't help in this situation. (I do not work >>for Trello.com) >> >>Long story short, it's kanban in the cloud and can be adapted for just >>about anything. It's free, too! My son's multi-age, non-traditional >>school -kids, teachers, and parents alike- use it to track student projects >>& goals, plan school events, fundraising, wish lists, supplies lists, and >>more. It's easy to use, share, and collaborate. It works in the browser >>or you can use their mobile apps. You can set up checklists, attach images >>and files, work with due dates, comment and activity streams, etc. Plus, >>using their RESTful API, you could whip up some slick automation and >>reporting (using Python, of course!) >> >>I'll be glad to help you and your wife off-list if you'd like some >>pointers. >> >>Good luck! >> >>Dave > > boB: this was precisely the sort of solution 'already existing in the > cloud' I was hoping you could find. I just didn't know about this one. > Very cool. Thank you Dave. I will forward this to Vonda and see what she thinks. But from what she has described thus far, I don't think it will give her the type of interface she is hoping to get, or make it easy to organize her information in the way she seems to want. However, it looks like it might do some stuff that I have wanted done on my phone that I used to do on a Palm once upon a time. I will have to glance at the API docs and see what else we might do with it. Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design question: Web-based vs. desktop-based vs. desktop-based with data backed up to web server with a tablet thrown in for all cases?
On Sun, Jul 19, 2015 at 1:27 AM, Steven D'Aprano wrote: > On Sun, Jul 19, 2015 at 12:49:50AM -0500, boB Stepp wrote: > >> In this thread, I kept it very general on purpose. I was probing this >> community for their thoughts on two things: 1) Should I make the >> software web-based or desktop-based? 2) What would be the best way of >> handling the data involved, particularly the data that impinges on >> student privacy concerns. > > Not to be a wet blanket, but this is way off-topic for this mailing > list. However, you're a regular in good standing, and we don't have a > strict rule about staying on-topic (such rules are tiresome and annoying > if they allow for no exceptions), so let's go with it. Thanks for the pass! But I actually thought this was on-topic. I am preparing to write a Python application. I have some questions about how to design it. Why would this be off-topic? I get it that program design applies to all programming languages, but since this list is targeted to people learning programming, I would think we would all need help in these areas, too. Otherwise our Python programs would not be very well written, however correct the Python syntax might be. For the rest of your answer, I think that this is exactly how I should approach this first program. And after having a discussion with Vonda today, it is actually her intent--play with this project until it is in a form that works in her workflow, and then expand upon it. Laura suggested kivy, too, and I think it will best do what is needed for the Slate tablet. Alan's and your suggestion to use SQLite seems a good one as well for the prototype. Thanks to everyone who responded to this thread. It has really clarified my thinking on the best way to get productive as quickly as possible. Now to find the energy after my regular work and the time at home which is always being taken up by my two kids and Vonda! Would it be off-putting later to ask specific questions about implementing features of kivy on this list? I imagine that they would tend to be basic questions that would probably apply to any GUI development. But I'm sure there is a kivy list somewhere once I look for it if I need to go there. I took Laura's suggestion and asked my original questions that started this thread on the tkinter list she suggested, but I have yet to receive an response. One thing I cherish about this list is it is both active and enthusiastic in providing help and direction, even if that help is to suggest other avenues for help. Much better than silence! Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design question: Web-based vs. desktop-based vs. desktop-based with data backed up to web server with a tablet thrown in for all cases?
On Sun, Jul 19, 2015 at 8:23 PM, boB Stepp wrote: > Would it be off-putting later to ask specific questions about > implementing features of kivy on this list? I imagine that they would > tend to be basic questions that would probably apply to any GUI > development. But I'm sure there is a kivy list somewhere once I look > for it if I need to go there. I guess I will answer this question myself: I have just been skimming through the kivy docs tonight and they look to be quite good. Also, I found their Google group and it looks to be quite active. So unless I have a GUI question that seems to fit better here, I will direct my kivy inquiries to their Google group. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] _ vs. _name vs. __name vs. name_ vs. __name__ usages
After having a long discussion with my wife on her user requirements, I am convinced that an OO approach is required. Which is just as well as that has been one of my next areas of learning to do. I am currently reading "Python 3 Object Oriented Programming" by Dusty Phillips, which so far seems to be a reasonably good text. This has led me to the subject line topics. >From my understandings to date: 1) A single underscore is used conventionally for a "throw-away" variable, such as a loop index for which the index value is not actually used in a subsequent calculation. 2) _name is used inside class methods to indicate that the programmer's intention is that this name should only be accessed internally by that particular class. Other supposedly "adult" Python programmers will attempt to respect this original intent if they use my code. 3) __name invokes Python's name mangling mechanism. The intent of this usage is to not allow subclasses of the class containing __name to access this name, and to add additional emphasis to future users of my code that this name is meant to be strictly hands-off. 4) name_ is used when one is "forced" to use one of Python's reserved words as a name. 5) __name__ is meant to be used only by the creators of Python for their special built-in methods, such as __init__, __new__, etc. Are my understandings above correct or flawed? For (3), it seems to me that one would normally be able to use the simpler _name construction from (2). What would be a best-practice example of when name mangling *should* be used? Likewise, it seems that normally (4) should never be needed, though I have a feeling that I have seen something in tkinter recently that suggests some exceptions, but I cannot (yet) bring it to mind. And for (5), surely I should never violate this one? It seems that in some future edition of Python they might add any particular __name__ that I might try to use presently in their future version of Python (however miniscule that possibility might actually be). Thanks! boB -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] OT: Test to see if ibisMail app is truly sending in plain text
I apologize for the noise, but I felt it better to get this question answered definitively prior to posting questions from my iPad. I am on a brief vacation and only brought my iPad. I have been having a devil of a time searching the Internet for an iPad app that will truly send and display in plain text emails. If someone would tell me if I have been successful or not, I would be very appreciative! If successful, Python questions will soon follow. Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to design object interactions with an SQLite db?
I have never written programs to interact with a db. I have never written an OO program. So this is getting interesting rather quickly! As I continue to ponder my project design, I see many of the classes I wish to create map naturally to db tables. For instance the class Student can potentially have many data attributes, which fit naturally into its own db table. My current thoughts are that I have two main ways of approaching this: 1) Create my various objects normally, but have their data attributes fetched through some sort of db manager class I would design. 2) Use an ORM (Object-Relational Manager) such as SQLAlchemy to manage interactions between my objects and the SQLite db. Both routes will be quite educational for me. Option (2), if I am understanding things correctly, would be more likely to make it relatively easy to change from SQLite to a more sophisticated server-based db in the future incarnations of this project. Thoughts? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Test to see if ibisMail app is truly sending in plain text
Well, in replying to your message, Steve, I see that this is not the perfect iPad solution. After hitting reply all, it failed to give attribution to your comments. But as I have not been able to find anything better, I guess I can manually add attribution names, and make this work on the rare times when I must communicate with programming fora from my iPad. At least you have demonstrated that it is truly in plain text! I show in its entirety what I see just for the record: > On Sat, Aug 01, 2015 at 10:27:27AM -0500, boB Stepp wrote: > > > I apologize for the noise, but I felt it better to get this question > > answered definitively prior to posting questions from my iPad. > > > > I am on a brief vacation and only brought my iPad. I have been having > > a devil of a time searching the Internet for an iPad app that will > > truly send and display in plain text emails. If someone would tell me > > if I have been successful or not, I would be very appreciative! If > > successful, Python questions will soon follow. > > Yes, plain text. > > According to the full headers of your email, you are sending from: > > X-Mailer: ibisMail for iPhone ver.4.0.9 > > with content: > > Content-Type: text/plain; charset="us-ascii" > > > -- > Steve > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Test to see if ibisMail app is truly sending in plain text
On 2 Aug 2015 Oscar Benjamin wrote: > Have you tried using the Gmail app? Yes. That is my normal mail app. > I'm using the Gmail app here on my phone. I've just looked at your message, > hit reply-all and then "respond inline". Then I can see/edit the > attribution line and your message. I've not had complaints with using the > list this way (perhaps I'm inviting them now though!) That is how it works on my Nexus 5 phone, though I have not attempted to send an email to this list yet from it. However, on my iPad, this functionality is not present in the Gmail App. Why it would not be beats me, but unless there is a hidden setting or gesture I have missed, both by futzing around my actual iPad as well as searching the 'Net, then it is not available. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to effectively use a Student class with SQLite [Was Re: How to design object interactions with an SQLite db?]
Beware! Lengthy post!! Sign of a confused boB. ~(:>) I believe that I understand now all of the things I want my project (Tentatively named "Montessori Classroom Manager".) to *do*. But I am currently spinning my wheels on how to implement classes, SQLite, and the kivy UI, so that they all effectively interact with each other. I think it is time to write some code and that I should start with the most fundamental class to the project, the Student class. The Student class, as I now envisage it, will have many attributes, which seem to naturally map to a Student db table. The first issue that I am puzzling over is the very real possibility of duplicate student names. Of course, I was planning on the Student db table having a primary key of student_id, which would be an unique identifier for a particular student. The problem with this is from the user's perspective: The teacher will naturally want to interact with the program using the student's name, possibly even a student's nickname. These can be non-unique. I like Alan's suggestion: On Sat, Aug 1, 2015 at 12:30 PM, Alan Gauld wrote: > On 01/08/15 17:34, boB Stepp wrote: >> 1) Create my various objects normally, but have their data attributes > >> fetched through some sort of db manager class I would design. > > Personally I tend to create a load() method that is used like a constructor > but fetches the data from the database > > myObj = MyClass().load(ID) > > Where load() returns self if successful. > Alternatively in Python you could define the ID as a parameter of init with > a None default > > def __init__(self,att1=None,att2=SomeDefault,...,ID=None): > if ID >self.load(ID) > else: >self.att1 = att1 # etc... > > Its conceptually simple and gives you full control of the SQL, but things > like inheritance can get tricky. Both his ideas rely on using the primary key for a student to fetch the information needed to create that particular student object, which the user will not normally ever use directly. So this leads me naturally to the UI design, something I would normally mostly forget about until I had my main program logic well worked out. But in this project it seems to me that program logic, db and UI are all intimately intertwined. In terms of UI I imagine the user will have some sort of list of student names displayed. In a given school year in the case of two students with identical names, I imagine the target user (my wife) will want a student nickname displayed to differentiate between two (or more) such students. So she would select a student in the UI and start doing stuff. I assume if I have a list of student names in the UI, then the program already created all of the student objects in the list, so the student_id primary key for each student would be freely available to use. However, if the student did not exist in the list, then a new student object would have to be created and its relevant attributes recorded in the student db table with its newly created student_id primary key. So (Finally!) if I am understanding the important issues involved in creating a viable Student class, I should be doing: 1) For the current school year, at program startup, the program should retrieve all current students' attributes from the db, instantiate each such student object, and be able to make each available in the UI. 2) If a new student needs to be created by the user, then the Student class would have an appropriate method which would allow for data entry via the UI to both create a new student object and a new student db table entry with its own unique student_id primary key. 3) The program logic would reference each student object only with the student_id primary key uniquely associated with each such student object. Is this the way to approach this, or at least a good way? I don't want to worry about actually coding the UI at this point, but it looks like while testing things as I go along, I will need to have at least a text simulation of a UI, so I can try selecting students, creating students, etc. Would the best way to go about this is to create an old command line-style menu system, which lists options by number, input number desired, action occurs etc.? As always, many thanks in advance! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to effectively use a Student class with SQLite [Was Re: How to design object interactions with an SQLite db?]
Whew, Alan! You've given me quite a lot to mull over. Thank you very much for the time you've invested in your responses!! On Thu, Aug 13, 2015 at 6:38 PM, Alan Gauld wrote: > On 13/08/15 20:18, boB Stepp wrote: > [...] > Yes, that's a standard problem in any HR type application. Names suck as > database keys. But names are how humans interact. HR = Human Resources? > > The only way around it that I know is for you to assign and use > student IDs in the code but on the UI use search screens that > 90%+ return one student but occasionally return 2 or 3 (rarely > many more) and the user has to figure out which one they want.. I've had this rattling around in my brain when I sent my post. > If you have a search form you have to check for multiple responses before > filling the form. If its true then pop up a list dialog > to let the user pick... It looks like I would need to query the db for all students with this same name, and display enough additional info for each student to enable the user to select the correct one? And once that selection is made I would have the student_id needed to pull info out of the db? It looks like there may be an edge case problem that can slip through the cracks: As the user will be doing her own student data entry, in the case of students with duplicate names, she might forget to enter one (or more, if there are that many). The program would return only one name, suggesting no name duplication exists, and might cause the user to start editing that student's info when she really needs to do is create the student entry which she forgot to do so in the first place and edit that student's data. It seems that I would always have to display a certain amount of student information to make it *obvious* to the user which student she is editing. Or is there an easier way? > > But many colleges now issue student cards with a unique ID. So the problem > may not be as hard as you think. My wife is dealing with 7th through 9th graders, not college level. Her school does not assign student id numbers, so I would have to have the program generate unique ids numbers. >> So this leads me naturally to the UI design, something I would >> normally mostly forget about until I had my main program logic well >> worked out. But in this project it seems to me that program logic, db >> and UI are all intimately intertwined. > > > Hopefully not, you can create a web/desktop or CLI UI. > The UI (or specifically the Controller in MVC terms)... I'm guessing this stands for "Model-view-controller" as in https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller > ...may well dictate or at least influence the API to the > data (or Model in MVC terminology.) The display (View in MVC) > part of the UI should typically be driven by the API rather > than the other way round. I may be getting bogged down in terminology here. In this MVC design, is the controller serving as the API between the data (model) and the display (view)? So is the idea here to decouple the program logic from the (possibly complicated) UI, is to have a module (controller?) which processes data resulting from the program logic (model) and then decides whether this should go to the menu portion of the display, or the part that generates a pop-up window, etc.? And likewise user-generated events go to the controller module and it decides which data states get altered in the model? And IF I am understanding this correctly, the program logic (model) and controller need to be designed in parallel? > > The other thing that can really help is to use the Use > Case methodology. Write out the interaction dialog between > user and system for the "happy path" scenario for a given task. > Then analyse each step in turn for potential error cases and > write out the use case for how you'd handle each error type. > There is a ton of Use case material online. It's a very powerful technique > and since its text based, there's no new tools to learn. This is new to me, but I have always tried to think along these broad lines in other projects I have done. I will have to search for most applicable materials to my current project. >> So (Finally!) if I am understanding the important issues involved in >> creating a viable Student class, I should be doing: >> >> 1) For the current school year, at program startup, the program >> should retrieve all current students' attributes from the db, >> instantiate each such student object, and be able to make each >> available in the UI. > > > Maybe not. You could have a report object that displays a subset > of student attributes without creating an object per student. > Then only when it comes time to modify or operate on a studen
[Tutor] Does composition only work with particular instances of objects?
I was looking at an example illustrating composition from the book, "Introducing Python" by Bill Lubanovic on p. 140: >>> class Bill: def __init__(self, description): self.description = description >>> class Tail: def __init__(self, length): self.length = length >>> class Duck: def __init__(self, bill, tail): self.bill = bill self.tail = tail def about(self): print('This duck has a', bill.description, 'bill and a', tail.length, 'tail.') Here I was mildly surprised that bill and tail were not Bill and Tail, and in the about method that self.bill was not used in place of bill.description, etc. Continuing: >>> tail = Tail('long') >>> bill = Bill('wide orange') >>> duck = Duck(bill, tail) >>> duck.about() This duck has a wide orange bill and a long tail. So I naively thought I could do the following: >>> bill0 = Bill('narrow rainbow') >>> tail0 = Tail('ginormous') And was surprised by: >>> duck.about() This duck has a wide orange bill and a long tail. >>> duck0 = Duck(bill0, tail0) >>> duck0.about() This duck has a wide orange bill and a long tail. >From this I am forced to conclude that composition will only work with particular instances of objects and not with any old objects created from their respective classes. Is this understanding correct? Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to effectively use a Student class with SQLite [Was Re: How to design object interactions with an SQLite db?]
On Thu, Aug 13, 2015 at 11:13 PM, Laura Creighton wrote: > If your students need to provide a unique email address, then that is > a possibility to use to distinguish between ones with the same name. Many of my wife's students do have their own email accounts, but, alas, not all of them. I have not totally thought this through yet, but the student data will include their parents' names and some of their data. But it will be my luck that two students will have the same name, John Allan Smith, with their dads having the same name! But I guess I can list both parents' names. Surely that would enable the user to reliably pick the correct student? As an aside, when discussing my wife's user requirements for this project, I found out that some of her students have, shall we say, a variety of parents: birth parents, multiple step-parents, parents who are not allowed to have contact with their children, legal guardians who are not parents, etc. Ay, yi, yi! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Does composition only work with particular instances of objects?
On Thu, Aug 13, 2015 at 11:46 PM, Zachary Ware wrote: > On Thu, Aug 13, 2015 at 11:31 PM, boB Stepp wrote: >> I was looking at an example illustrating composition from the book, >> "Introducing Python" by Bill Lubanovic on p. 140: >> >>>>> class Bill: >> def __init__(self, description): >> self.description = description >> >>>>> class Tail: >> def __init__(self, length): >> self.length = length >> >>>>> class Duck: >> def __init__(self, bill, tail): >> self.bill = bill >> self.tail = tail >> def about(self): >> print('This duck has a', bill.description, 'bill and a', >> tail.length, 'tail.') >> >> Here I was mildly surprised that bill and tail were not Bill and Tail, >> and in the about method that self.bill was not used in place of >> bill.description, etc. Well, I was wrong about "Bill" and "Tail", but, then again, that came from trying to make the flawed example work as I thought it should work with things like: class Duck: def __init__(self, Bill, Tail): self.bill = Bill.__init__.description etc. Which, of course, I could not make work. But I should have explored adding the "self" where I thought it should have been used. > Something went wrong here, either with the example itself or your > copying of it... Alas, it is an error in the book. The only alteration I made in the author's code was to drop the parentheses after the class names, that is, I used "class Bill:" instead of the author's "class Bill():". I also added a "." after "'tail'" in the about method, but that truly is an itty, bitty thing. > ...Your instinct is correct, it should be > 'self.bill.description' rather than 'bill.description': the Duck.about > method as written above will only work in situations where 'bill' and > 'tail' happen to be defined in the calling scope. The about method > should be: > >def about(self): >print('This duck has a', self.bill.description, > 'bill and a', self.tail.length, 'tail.') > > >> Continuing: >> >>>>> tail = Tail('long') >>>>> bill = Bill('wide orange') >>>>> duck = Duck(bill, tail) >>>>> duck.about() >> This duck has a wide orange bill and a long tail. > > Before you fix the about method as I suggested above, try this again > but do `del bill, tail` before you call `duck.about()`; the failure > may be somewhat enlightening. Yeah, I was dead certain that the book's example as written would only work for the particular objects "bill" and "tail" and not for any objects used for those in "Duck(bill, tail)" and this made absolutely no sense to me. Why limit composition to work with only particular instances of objects??? I probably should have gone ahead and played with the substitutions you suggested. "bill.description" and "tail.length" just did not make any sense to me. Thanks, Zach! I will have to see if the book has an errata site. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to effectively use a Student class with SQLite [Was Re: How to design object interactions with an SQLite db?]
On Fri, Aug 14, 2015 at 4:49 AM, Laura Creighton wrote: > You've found the 'variety of parents' problem. Listing the parents' > names will only let your wife know she has the correct student if she > habitually thinks of the parent names when she thinks of the student. This came to mind because currently, even with three grades in the same classroom, the total number of students tends to be small compared to traditional schools. Also, Montessori parents seem on average to be very active in their comms with the teacher. But... > I suspect her internal labelling is more likely to be along the lines > of 'the short one', 'the one who plays the cello', 'the one who used > to have difficulty reading' and 'the one whose water-pistol I > confiscated in the first week of class'. > > So you may be better off letting the teacher specify some tags she can use > and apply to any student, which can be of use when you need to > tell one student from another, and the name just isn't doing it for you. > (Perhaps because you have several students with that name, but also because > this is a student you taught many years ago. The name is vaguely > familiar but the details have blurred over time. "Water-Pistol" will > evoke better memories than parents' name in this case, as if you can > barely remember the child you most likely have lost the parents altogether.) ... I have been thinking in terms of only my wife using the software. If I have the good (or mis-) fortune to create a successful and utile bit of software, I might find others using the program. So your points suggest I should look for a more flexible approach that any potential user will find effective. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Does composition only work with particular instances of objects?
On Fri, Aug 14, 2015 at 2:50 AM, Alan Gauld wrote: > > So, unless the book explains why this is bad practice and > goes on to show a good example, I must conclude its a very > bad example. I found the errata pages for the book (http://www.oreilly.com/catalog/errata.csp?isbn=0636920028659) and a Jeff Bienstadt submitted this on Aug 05, 2015. Mr. Bienstadt did a fine job of making his points. The author acknowledged his errors with: "Thanks for catching this. You are completely correct, and your example code proves it. I regret the error. I would blame my cat, but this one wasn't his fault." So obviously the quality control process let this one slip through the cracks. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cannot get a label message to display immediately
On Fri, Aug 14, 2015 at 11:32 AM, Bill Allen wrote: > > I am working in Tkinter. The scenario is that I click a button that > starts a function running. No problem there. However, the function may > take some time to run and I do not want the user to be worried. I am > wanting to immediately set a label when the function starts to say "Please > Wait". However, the label does not show up until the function completes. > How do I get both actions to happen essentially at the same time, the > writing of the label and the execution of the function? I have no code to > show on this one because I am lost in the weeds, not sure of the general > way to go on this. I am on the path to learning myself, but couldn't you, as part of the function, have it either set the label itself or call another function that does this, and then execute the main part of your function? Also, just before your function returns its result, it could clear/rewrite the label. Additionally, tkinter has the ability to change the cursor to an hourglass. You could handle this analogously to what I already said. HTH, -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] SQLite, Python and SQL injection attacks
I was just looking at the sqlite3 docs at https://docs.python.org/3/library/sqlite3.html?highlight=sqlite#module-sqlite3 and found the following cheery news: "Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack ..." There followed this recommendation: "Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method..." I have to be honest -- I would have fallen into this potential trap if I had not read this. It is not clear to me yet how the recommendation avoids this issue. Does the placeholder enforce some sort of type checking so that arbitrary SQL strings will be rejected? Having seen this example, are there any other security surprises that I need to avoid by adopting certain coding techniques when I am using Python with SQLite? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try and file existence
On Fri, Aug 14, 2015 at 10:39 PM, Steven D'Aprano wrote: > > On Fri, Aug 14, 2015 at 06:28:09PM -0700, Clayton Kirkwood wrote: > > what is the best way to find out if a file exists? > > Try to open it and see what happens. If the open() succeeds, then the > file exists and can be read. If it fails, then either the file doesn't > exist, or it can't be read. Inspect the error to find out which. > > There is also os.path.exists(filename), but you should avoid using that > if possible. The problem is this: > > if os.path.exists(filename): > # file exists *right now* > # but a millisecond later, some other program deletes it... > # and now it doesn't exist any more > with open(filename) as f: # gives an error > ... I understand your points, but wonder then what is the intended use for os.path.exists()? That is, in what types of circumstances would it be both appropriate and safe to use? boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How best to determine if a db exists before trying to open it? [Was: try and file existence]
On Sat, Aug 15, 2015 at 6:00 PM, Cameron Simpson wrote: > On 15Aug2015 15:20, Clayton Kirkwood wrote: >>> >>> Behalf Of Laura Creighton > > [..] >>> >>> To: boB Stepp >>> In a message of Sat, 15 Aug 2015 14:24:21 -0500, boB Stepp writes: >>> >I understand your points, but wonder then what is the intended use for >>> >os.path.exists()? That is, in what types of circumstances would it be >>> >both appropriate and safe to use? >>> >>> If you want to locate dangling symlinks, os.path.exists will return >>> False, so >>> the symlink is there, but the file it pointed to is long gone. >> >> >> Can't you do that with os.path.open() and get a value in os.path.status? >> (I >> think that is the thing to call) > > > Open does more that os.stat (which is what os.path.exists uses underneath). > > There are plenty of times you will want to know a file exists but not have > permission to open it. Also, open can have side effects if the target file > is a device or a socket/pipe. > > Always use the smallest thing you can to achieve an effect: stat is smaller > than open. I actually had a specific example in mind when I asked my question. My current project will require me to create and then use an SQLite db. My concern is that after: import sqlite3 db = sqlite3.connect("my_db.db") 1) This will open the db if it exists already, which is normally what I will want. But... 2) My understanding is that if for whatever reason the db file is not found, then the connect statement will create a new instance of the db, which is what I normally would not want (Except at the time of initial creation). I'm just now in the process of reading up on SQLite, SQL, and Python's DB API. So far I have seen no mention that the connect statement returns anything if the db file does not already exist. If I am understanding everything so far, I think that my situation would be appropriate for using os.path.exists(). Is this correct? Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try and file existence
On Sat, Aug 15, 2015 at 6:41 PM, Steven D'Aprano wrote: > On Sat, Aug 15, 2015 at 02:24:21PM -0500, boB Stepp wrote: >> I understand your points, but wonder then what is the intended use for >> os.path.exists()? That is, in what types of circumstances would it be >> both appropriate and safe to use? > > def print_file_names(possible_names): > print("List of file names checked") > print("--" > for name in possible_names: > if os.path.exists(name): > print(name) > else: > print("missing:", name) Your example, giving about the most benign possible uses, is for emphasis? boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Where should unit test files go in a project directory structure and some related questions?
In this Montessori Classroom Project (mcm) I am working on, I hope to incorporate as much of the advice I've gotten here as I can remember. So I want to do version control, TDD, etc., and do it as well as I can. Especially since this thing looks to grow considerably over time. I have not ever thought about formal project directory structures before, so I may need a bit of guidance here. My current skeleton structure is: /Projects /mcm /.git /db __init__.py /ui __init__.py main.py My intent is to use main.py to start the program. I know I am going to be using a database and a user interface, thus their folders. I don't yet have a feeling for how many additional directories I might have for the bulk of the program logic code. Right now I am trying to figure out how to arrange my unit test file(s). My initial thoughts are to have a single test directory with separate subdirectories corresponding to each folder which has source code. Is this a good way to do things? While searching through the Tutor archives I found one of Steve's answers on project structure, which I copied part of below. Unfortunately it did not address testing organization: --- Re: [Tutor] Project directory structure Steven D'Aprano Thu, 30 Jan 2014 03:26:22 -0800 If you're creating something a little more formal, say you plan to make it public, there is a convention for laying out project directories: myproject +-- CHANGES.txt +-- LICENCE.txt +-- MANIFEST.in +-- README.txt +-- setup.py +-- src +-- myproject.py although the src directory is not compulsory. If you're creating a package, rather than a single module, then you do need to use a special directory structure: mypackage +-- __init__.py +-- __main__.py +-- cheese.py +-- eggs.py +-- spam.py --- It looks like I ought to combine the myproject and mypackage recommendations into a coherent whole. It looks like my current subfolders of /db and /ui as well as main.py should go under the subfolder /src. The suggested files CHANGES.txt, LICENSE.txt, and README.txt look like good things to include. I don't know yet what MANIFEST.in is about. Makes me think of a shipping manifest, but that is probably not its function. And I don't know what set-up needs setup.py would typically serve. I will have to search for answers to these. Does this cover everything I need to be concerned about as far as project organization so that I do not run into future problems? TIV! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where should unit test files go in a project directory structure and some related questions?
On Sat, Aug 15, 2015 at 9:10 PM, boB Stepp wrote: > Right now I am trying to figure out how to arrange my unit test > file(s). My initial thoughts are to have a single test directory with > separate subdirectories corresponding to each folder which has source > code. Is this a good way to do things? Apparently, based on tonight's searching, there is a large diversity of opinion on where to put one's tests! I did find one good web article, "Python Project Howto", at http://infinitemonkeycorps.net/docs/pph/ that seems really good. It is oriented on how to prep your project for open source distribution and is quite detailed. On the question I am interested in, the author proposes this project structure: googlemaps/ # Project Hosting .svn/ # Version Control googlemaps/ # Quality Code googlemaps.py test/ # Unit Testing test_googlemaps.py doc/ # Documentation index.rst html/ index.html README.txt LICENSE.txt # Licensing setup.py # Packaging MANIFEST.in I think that this article would make a good read for anyone in a similar learning situation as mine. Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor