[Tutor] I want to share a source that i wrote
Hi guys, i wrote a simply MySQL interpretar with Python / Tk and I want to ask if can I share with the people in the list to discuss about the code and maybe help to the community. The source code has 200 lines and is written in a single file. P.D. please, Alan Gauld be kind with my mistakes about code or about my words, I speak Spanish natively and English a little bit. P.D.2. Alan it's only a joke, sorry in advice! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I want to share a source that i wrote
On 15/01/16 01:11, Ricardo Martínez wrote: > Hi guys, i wrote a simply MySQL interpretar with Python / Tk and I want to > ask if can I share with the people in the list to discuss about the code > and maybe help to the community. > > The source code has 200 lines and is written in a single file. That should be OK. Anything over 200 lines is quite big so you could try using a pastebin instead of posting it by mail, its up to you. posting is more convenient to read and to respond to, but pastebin has the advantage of syntax colouring etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Re: creating a mspaint utility
forwarding to tutor list... please use ReplyAll when responding to the list. Forwarded Message Subject:Re: [Tutor] creating a mspaint utility Date: Fri, 15 Jan 2016 16:07:36 +1000 From: Whom Isac To: Alan Gauld Hi, Alan Gauld, in regards to the response I got from you, I am using python 3.4 while writing the code but normally use 3.5. And this is just a practice tutorial that I thought about my self to make it because I know GUI-canvas can let you draw if you know the coordinates. I thought maybe you can get the mouse positions and put them in order to draw a line,etc. I see you identified some issues which I have problem with because I know mistakes already but You see if you have run the code into an interpreter or IDLE it would show you the mouse co-ordinates each time you right-click on the canvas (not the tkinter, intentionally) to draw. I did not want to use global variable because I am not used to this function in python or any lambda function because it's quite hard. And for original Mouse position function: > label=Label(frame1,text="XY",relief=GROOVE).pack(side=BOTTOM, > anchor="ne") > label1=Label(frame1,text=str(show_event), > relief=SUNKEN).pack(side=BOTTOM, anchor="ne") > return I wanted to show the mouseposition under a label with X and Y (at the GUI-startup). Then if mouse position changes then make another label underneath with the current mouse position with MousePosition method: >def mouse_position(): >show_event=app.winfo_pointerxy() >(X,Y)=show_event >if ''!=show_event : >show_event=app.winfo_pointerxy() >(X,Y)=show_event >print("Current mouse are on: X:{0} Y:{1}".format(X,Y)) >label2=Label(frame1,text=str(show_event), relief=GROOVE).pack(side=RIGHT) And you are right that I have to call the same code to find the mouse-position again and again. Because I think if you don't right the variable first or inside the function it will not work. Then again I don't know what got me but I thought that I could write a function for mouse pressed which will print(Right Click has been pressed.) and take a variable to store the mouse position. Now I think I can modify the code to use separetely to find the coordinates but I don't know how to do that. Because in each right click the initialpos and finalpos of the mouse will change and they would have the same value. Should not they?? That's why I got so confused and made a plan to write a small code with it so it will compare final position and initial position with this: >finalpos=(0,0) > if initialpos !=finalpos: > if Mouse_pressed(event): > finalpos=app.winfo_pointerxy() It's not possible for final position to be (0,0) which I know better so it would make the function to store a new finalposition. This attempt failed so I comment them out. This is the same trick I used for getting the initialposition which you did not include. So no point in arguing about who is wrong. If you had tested the code you might have notice that each time I am pressing the show button the command keep printing or making a label to the right. How do I keep only a single label and delele the old label. And each time I click on the canvas initialposition and finalposition become the same value. And even though I made sure the label-Original Mouse Position should be followed by(" X Y ") and the mouse position underneath the order is not right when I run the GUI. So any idea how should I store the initial and final position e.g. inside a function or as global value.?? or An advice to what should I do about mouse position functions? Should I reduce any of them? Is it a problem to put labels inside them? If you have not run the GUI yet, here are some of the snapshot I took: On Fri, Jan 15, 2016 at 10:50 AM, Alan Gauld mailto:alan.ga...@btinternet.com>> wrote: On 14/01/16 10:58, Whom Isac wrote: > Hi, I was wondering if it is possible to make a similar drawing tool with > basic functionality to draw lines, circles or square with python canvas. Yes of course and there are at least a couple of online tutorials on how to do that. Google is your friend. > I did not think it would have been a difficult work but I have spent 3-4 > hours and out of luck. I get my functions to give me the mouse position > while moving, when pressed, original position or current position. But > don't know how to store them as a value. Use variables just like any other value. GUI work is always harder than you expect and ful;l of frustrating details. 3-4 hours on a GUI project is not long at all. > I am not a genius and is not used to tkinter very well (to use command > function or anything) to store a value. Which tkinter tutorial are you reading? > import tkinter as tk > from tkinter import * > import sys > #app GUI > app=tk.Tk() > app.title("
Re: [Tutor] Fwd: Re: creating a mspaint utility
On 15/01/16 08:34, Alan Gauld wrote: > maybe you can get the mouse positions and put them in order to draw a > line,etc. Yes, that's a valid approach to building a multi-segment line. Normally you store the points in a list somewhere. > I did not want to use global variable because I am not used to this > function in python or any lambda function because it's quite hard. You can avoid lambdas but I think you need to use globals to get this to work. You are already using some global variables in your code, you just need to identify which ones you want to change in your functions. That's simply done using the global keyword, so your function would look like: def some_function(event): global widget_name etc... widget_name = new_value etc... It is really quite easy and allows you to store information from inside a function so that other functions can see it. The alternative strategy involves creating classes and objects but that is possibly too advanced for you just now. The problem with your existing code is that you are creating the widgets inside functions. But when the function ends you lose all references to those widgets so you cannot modify them or even read them in any way. (Although the variables all currently refer to None because you use pack() in the same line as you create them.) >> def mouse_position(): >>show_event=app.winfo_pointerxy() >>(X,Y)=show_event >>if ''!=show_event : >>show_event=app.winfo_pointerxy() >>(X,Y)=show_event >>print("Current mouse are on: X:{0} Y:{1}".format(X,Y)) >>label2=Label(frame1,text=str(show_event), > relief=GROOVE).pack(side=RIGHT) > > And you are right that I have to call the same code to find the > mouse-position again and again. Actually you don't really need a function there, I just realized you can simplify it by just rewriting it as a single line: X,Y = app.winfo_pointerxy() > Then again I don't know what got me but I thought that I could write a > function for mouse pressed which will print(Right Click has been > pressed.) and take a variable to store the mouse position. Now I think I > can modify the code to use separetely to find the coordinates but I > don't know how to do that. Because in each right click the initialpos > and finalpos of the mouse will change and they would have the same > value. Should not they?? Sorry, I'm not sure what you mean there. Can you try explaining again please? > If you had tested the code you might have notice that each time I am > pressing the show button the command keep printing or making a label to > the right. How do I keep only a single label and delele the old label. You need to create a global variable and then update that label. > So any idea how should I store the initial and final position e.g. > inside a function or as global value.?? Anything that you do in one function that you want to be visible in another function (or even the same one called a second time) will need to be stored in a global variable. Variables inside functions get deleted as soon as the function exits so you cannot refer to them again. Each time the function gets called it creates a new set of variables it does not use the same ones as the last time. > about mouse position functions? Should I reduce any of them? Is it a > problem to put labels inside them? Its OK to create labels inside but they will always be new labels unless you use global variables. [Note 1: Strictly speaking there are some other ways to maintain data between function calls but I'm pretty sure they are too esoteric for your purposes. Globals or classes are by far the simplest solutions Note 2: Technically the widgets you are creating do have references outside the function, otherwise they would be destroyed, but to reach them involves traversing the app object's containment tree which is relatively complicated and error prone ] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Re: creating a mspaint utility
Might I also recommend Kivy as the GUI. It has a nice tutorial that is actually on this subject. https://kivy.org/docs/tutorials/firstwidget.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Modularity
Modularity of code is difficult for sure and is kind of an art. To do it best you will have to read about and implement some of the Design Patterns. There are many but some of the ones that I have leaned towards over time are Composition over inheritance, Message Passing Interfaces, Mediator, and Model View Controller. Each of these is a large subject in there own right; and how to use each in your use case takes care and consideration. You also will need to consider that there is a learning curve associated with each design pattern so you will loose some time as you try to learn the pattern before it will begin to save you time by making your code less coupled. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] str.strip strange result...?
#python2.7 >>> s="V01_1" >>> s.strip("_1") 'V0' Wouldn't you expect the result to be "V01" ? Cheers Jignesh ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] str.strip strange result...?
Jignesh Sutar wrote: > #python2.7 > s="V01_1" s.strip("_1") > 'V0' > > > Wouldn't you expect the result to be "V01" ? str.strip() doesn't strip off a suffix or prefix; its first argument is interpreted as a character set, i. e. as long as s ends/starts with any of the characters "_" or "1", remove that. If you want to remove a suffix you have to write if suffix and s.endswith(suffix): s = s[:-len(suffix)] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Message Passing & User Interfaces
I realize this is a higher level question; so please direct me as appropriate. I can not seem to find a good standard that is in practical use for controlling user interfaces via a message passing. Does any one have any links to such an example? I would be most grateful. Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Hard Drive wipe
#The function for writing random data to the disk. def random(): print "" os.system("/sbin/fdisk -l") print "" print "Please choose a device to kill. Remember if you want to" print "wipe the whole drive and not just a partition, you can" print "remove the number appended. Example /dev/sdc1 becomes /dev/sdc ." print "" device=raw_input("Enter device: ") print "" count=input("How many times would you like to wipe the device? ") print "" print "Writing changes to disk. All data on %s will be lost."%(device) print "" raw_input("Press Enter to continue, or Ctrl+C to exit: ") print "" lap=1 for i in range(count): print "Processing wipe count %s of %s..."%(lap, count) os.system(("dd if=/dev/urandom of=%s")%(device)) lap=lap+1 I need to know how to substitute for the drive letter for the following drives. sad-sdp also will need to wipe data from /dev/md1 I believe that the script is sound just sub's ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Substitution function needed
#The function for writing random data to the disk. def random(): print "" os.system("/sbin/fdisk -l") print "" print "Please choose a device to kill. Remember if you want to" print "wipe the whole drive and not just a partition, you can" print "remove the number appended. Example /dev/sdc1 becomes /dev/sdc ." print "" device=raw_input("Enter device: ") print "" count=input("How many times would you like to wipe the device? ") print "" print "Writing changes to disk. All data on %s will be lost."%(device) print "" raw_input("Press Enter to continue, or Ctrl+C to exit: ") print "" lap=1 for i in range(count): print "Processing wipe count %s of %s..."%(lap, count) os.system(("dd if=/dev/urandom of=%s")%(device)) lap=lap+1 I need to know how to substitute for the drive letter for the following drives. sad-sdp also will need to wipe data from /dev/md1 I believe that the script is sound just sub's ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Help!
Hi, So what I am working on is taking a csv file and only taking 2 columns from the spreadsheet and out putting that to a text file. Then taking those two columns and organize them by product(key) and outputting the description(values) that are associated. Some products have a lot of duplicate descriptions and I am trying to get the counts of those. I have a piece of code that takes anything greater then 5 and prints that and also anything 4 or less goes into an 'other' category with the counts.So what I am trying to do now is import a csv and change it to a text file with the same naming convention as the csv. Below is my functions code: import csv import json import sys from collections import defaultdict from collections import Counter class dictionary(): def __init__(self, filename): self.dict = defaultdict(list) self.counted_dict = defaultdict(list) self.grouped_dict = defaultdict(list) self.other_dict = defaultdict(list) self.final_dict = defaultdict(list) self.total_dict = defaultdict(list) self.txt_output = " " def populate_dict(self, filename): with open (filename, 'rb') as f: reader = csv.reader(f) next(reader, None) for row in reader: self.dict[row[2]].append(row[3]) def total_counts(self): for key in self.dict.keys(): total = 0 b = Counter(self.dict[key]) for value in b: total += b[value] self.total_dict.update({key: str(total)}) def all_counts(self): data_count = Counter() for key in self.dict.keys(): self.counted_dict.update({key: Counter(self.dict[key])}) def grouped_counts(self): for key in self.dict.keys(): total = 0 c = Counter(self.dict[key]) for value in c: if c[value] >= 5: self.grouped_dict.update({value: key + ': ' + str(c[value])}) elif c[value] <= 4: total += c[value] self.other_dict.update({key: 'other: ' + str(total)}) self.final_dict = self.grouped_dict, self.other_dict, self.total_dict, def txt_output(self, filename): a = filename.split('.') self.txt_output = a + '.txt' print a def json_output(self): with open (self.txt_output.txt, 'w') as text_file: json.dump(self.final_dict, text_file, sort_keys = True, indent = 4) What I am having issues with is the def txt_output that is where I am trying to take the .csv off and add the .txt but keep the filename the same. For example, having a filename "weekly_20160102.csv" and then create a txt filename with "weekly_20160102.txt" and have all the counts and products in the text file. Is there any way to do this? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Help!
Hi, So what I am working on is taking a csv file and only taking 2 columns from the spreadsheet and out putting that to a text file. Then taking those two columns and organize them by product(key) and outputting the description(values) that are associated. Some products have a lot of duplicate descriptions and I am trying to get the counts of those. I have a piece of code that takes anything greater then 5 and prints that and also anything 4 or less goes into an 'other' category with the counts.So what I am trying to do now is import a csv and change it to a text file with the same naming convention as the csv. Below is my functions code: import csv import json import sys from collections import defaultdict from collections import Counter class dictionary(): def __init__(self, filename): self.dict = defaultdict(list) self.counted_dict = defaultdict(list) self.grouped_dict = defaultdict(list) self.other_dict = defaultdict(list) self.final_dict = defaultdict(list) self.total_dict = defaultdict(list) self.txt_output = " " def populate_dict(self, filename): with open (filename, 'rb') as f: reader = csv.reader(f) next(reader, None) for row in reader: self.dict[row[2]].append(row[3]) def total_counts(self): for key in self.dict.keys(): total = 0 b = Counter(self.dict[key]) for value in b: total += b[value] self.total_dict.update({key: str(total)}) def all_counts(self): data_count = Counter() for key in self.dict.keys(): self.counted_dict.update({key: Counter(self.dict[key])}) def grouped_counts(self): for key in self.dict.keys(): total = 0 c = Counter(self.dict[key]) for value in c: if c[value] >= 5: self.grouped_dict.update({value: key + ': ' + str(c[value])}) elif c[value] <= 4: total += c[value] self.other_dict.update({key: 'other: ' + str(total)}) self.final_dict = self.grouped_dict, self.other_dict, self.total_dict, def txt_output(self, filename): a = filename.split('.') self.txt_output = a + '.txt' print a def json_output(self): with open (self.txt_output.txt, 'w') as text_file: json.dump(self.final_dict, text_file, sort_keys = True, indent = 4) What I am having issues with is the def txt_output that is where I am trying to take the .csv off and add the .txt but keep the filename the same. For example, having a filename "weekly_20160102.csv" and then create a txt filename with "weekly_20160102.txt" and have all the counts and products in the text file. Is there any way to do this? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] str.strip strange result...?
On 15/01/2016 16:25, Jignesh Sutar wrote: #python2.7 s="V01_1" s.strip("_1") 'V0' Wouldn't you expect the result to be "V01" ? Cheers Jignesh No, never expect anything from a given programming language. What did you not understand about this https://docs.python.org/3/library/stdtypes.html#str.strip when you read it? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] str.strip strange result...?
Gotcha and thank you for the reminder to read the documentation. Very clear, indeed. Many thanks! Cheers Jignesh On Fri, 15 Jan 2016 at 17:32, Mark Lawrence wrote: > On 15/01/2016 16:25, Jignesh Sutar wrote: > > #python2.7 > > > s="V01_1" > s.strip("_1") > > 'V0' > > > > Wouldn't you expect the result to be "V01" ? > > > > Cheers > > Jignesh > > No, never expect anything from a given programming language. What did > you not understand about this > https://docs.python.org/3/library/stdtypes.html#str.strip when you read > it? > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help!
Chelsea G wrote: > What I am having issues with is the def txt_output that is where I am > trying to take the .csv off and add the .txt but keep the filename the > same. For example, having a filename "weekly_20160102.csv" and then create > a txt filename with "weekly_20160102.txt" and have all the counts and > products in the text file. Is there any way to do this? The best approach is to solve small subproblems in a simple experimental file or in the interactive interpreter before you integrate the solution as a function that you have tested and found to be working as intended. If you look around the os.path module you'll find the splitext() function which works like this: >>> import os.path >>> os.path.splitext("/foo/bar/baz.ext") ('/foo/bar/baz', '.ext') To change the extension you can do >>> os.path.splitext("/foo/bar/my.csv")[0] + ".txt" '/foo/bar/my.txt' Now put it into a function: >>> def change_ext(filename, newext): ... return os.path.splitext(filename) + newext ... Let's test: >>> change_ext("/foo/bar/my.one", ".two") Traceback (most recent call last): File "", line 1, in File "", line 2, in change_ext TypeError: can only concatenate tuple (not "str") to tuple Oops, I made an error. Do you spot it? Let's fix it: >>> def change_ext(filename, newext): ... return os.path.splitext(filename)[0] + newext ... >>> change_ext("/foo/bar/my.one", ".two") '/foo/bar/my.two' Ok, this seems to work. You can do more tests (e.g. how will multiple extensions like "archive.tar.gz" or missing extensions like "somescript" be handled) and once it works as intended integrate it into your script. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Substitution function needed
On 15/01/16 17:07, Chad Perry wrote: > #The function for writing random data to the disk. > def random(): >os.system("/sbin/fdisk -l") >device=raw_input("Enter device: ") >count=input("How many times would you like to wipe the device? ") >raw_input("Press Enter to continue, or Ctrl+C to exit: ") >lap=1 >for i in range(count): >print "Processing wipe count %s of %s..."%(lap, count) >os.system(("dd if=/dev/urandom of=%s")%(device)) >lap=lap+1 > > I need to know how to substitute for the drive letter for the following > drives. > > sad-sdp > also will need to wipe data from /dev/md1 Sorry, it's not clear to me exactly what you want to substitute. Can you provide sample input and output? For example, if I input /dev/sda What do you want to happen? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is there a preference of "class MyClass:" or "class MyClass(object):" for Py3?
Pythonic style/preference question: For strictly Python 3 code, is there any preference for class MyClass: pass versus the more explicit class MyClass(object): pass ? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
At https://docs.python.org/3.4/library/stdtypes.html#sequence-types-list-tuple-range it states: "s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])" I find this confusing. First, at the interpreter, whenever I type in: >>> things [0, 'Hmm...', 3, 'WhackABunny', 6, '?'] >>> things[-1:-1] [] >>> things[0:0] [] I always get an empty list, which is actually what I was expecting, so I do not see how s[i:i] can ever equal [x]. The second thing I find puzzling is the docs say x is inserted at position i, while in the interpreter: >>> help(list.insert) Help on method_descriptor: insert(...) L.insert(index, object) -- insert object before index The "...insert object before index" makes sense to me, but "...inserts x into s at the index given by i..." does not because: >>> things.insert(-1, 'What the heck?!?') >>> things [0, 'Hmm...', 3, 'WhackABunny', 6, 'What the heck?!?', '?'] "...at the index..." to me would mean that 'What the heck?!?' should become the last item in the list. Again, the interpreter help gave what I was expecting. Am I just being dense or are the docs in this instance confusing? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
On 15Jan2016 22:20, boB Stepp wrote: At https://docs.python.org/3.4/library/stdtypes.html#sequence-types-list-tuple-range it states: "s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])" I find this confusing. First, at the interpreter, whenever I type in: things [0, 'Hmm...', 3, 'WhackABunny', 6, '?'] things[-1:-1] [] things[0:0] [] I always get an empty list, which is actually what I was expecting, so I do not see how s[i:i] can ever equal [x]. It isn't an equality test (==), it is an assignent. It is saying "set the zero length sequence at index i to the one element sequence [x]". The second thing I find puzzling is the docs say x is inserted at position i, while in the interpreter: help(list.insert) Help on method_descriptor: insert(...) L.insert(index, object) -- insert object before index The "...insert object before index" makes sense to me, but "...inserts x into s at the index given by i..." does not because: Personally I'd rather it said "insert object at index". For "before" I'd need something longer, like "insert object before the elements from index onward". things.insert(-1, 'What the heck?!?') things [0, 'Hmm...', 3, 'WhackABunny', 6, 'What the heck?!?', '?'] "...at the index..." to me would mean that 'What the heck?!?' should become the last item in the list. Again, the interpreter help gave what I was expecting. To me it means "insert 'x' so that its index is 'i'". Am I just being dense or are the docs in this instance confusing? They may be a bit confusing, though I do think you're misreading the "=" bit at the top. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
On Fri, Jan 15, 2016 at 10:53 PM, Cameron Simpson wrote: > On 15Jan2016 22:20, boB Stepp wrote: >> I always get an empty list, which is actually what I was expecting, so >> I do not see how s[i:i] can ever equal [x]. > > > It isn't an equality test (==), it is an assignent. It is saying "set the > zero length sequence at index i to the one element sequence [x]". Ah! That makes sense. > things.insert(-1, 'What the heck?!?') > things >> >> [0, 'Hmm...', 3, 'WhackABunny', 6, 'What the heck?!?', '?'] >> >> "...at the index..." to me would mean that 'What the heck?!?' should >> become the last item in the list. Again, the interpreter help gave >> what I was expecting. > > > To me it means "insert 'x' so that its index is 'i'". But that's my point! In my example x (here 'What the heck?!?') is *not* at index i (here, -1). Instead it winds up at index -2. But this fits in perfectly with the interpreter help, since it winds up *before* index i (-1). -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
On 15Jan2016 23:05, boB Stepp wrote: On Fri, Jan 15, 2016 at 10:53 PM, Cameron Simpson wrote: things.insert(-1, 'What the heck?!?') things [0, 'Hmm...', 3, 'WhackABunny', 6, 'What the heck?!?', '?'] "...at the index..." to me would mean that 'What the heck?!?' should become the last item in the list. Again, the interpreter help gave what I was expecting. To me it means "insert 'x' so that its index is 'i'". But that's my point! In my example x (here 'What the heck?!?') is *not* at index i (here, -1). Instead it winds up at index -2. But this fits in perfectly with the interpreter help, since it winds up *before* index i (-1). Ah, but -1 isn't the "real" index. It is a convenient value for computing the real index if you want to figure things out from the end of the list instead of the start. In your example above, the real index is 5. As you would get from things.index('?') before the insert. So your insert really means: things.insert(5, 'What the heck?!?') Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
On Fri, Jan 15, 2016 at 11:32 PM, Cameron Simpson wrote: > On 15Jan2016 23:05, boB Stepp wrote: >> >> On Fri, Jan 15, 2016 at 10:53 PM, Cameron Simpson wrote: >>> >>> things.insert(-1, 'What the heck?!?') >>> things [0, 'Hmm...', 3, 'WhackABunny', 6, 'What the heck?!?', '?'] "...at the index..." to me would mean that 'What the heck?!?' should become the last item in the list. Again, the interpreter help gave what I was expecting. >>> >>> >>> >>> To me it means "insert 'x' so that its index is 'i'". >> >> >> But that's my point! In my example x (here 'What the heck?!?') is >> *not* at index i (here, -1). Instead it winds up at index -2. But >> this fits in perfectly with the interpreter help, since it winds up >> *before* index i (-1). > > > Ah, but -1 isn't the "real" index. It is a convenient value for computing > the real index if you want to figure things out from the end of the list > instead of the start. In your example above, the real index is 5. As you > would get from things.index('?') before the insert. So your insert really > means: > > things.insert(5, 'What the heck?!?') Or, actual index = len(things) + (-1) before I do the insert. Another subtlety for negative indexing to file away! Thanks, Cameron. That wraps up things nicely for me. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a preference of "class MyClass:" or "class MyClass(object):" for Py3?
On Fri, Jan 15, 2016 at 09:30:57PM -0600, boB Stepp wrote: > Pythonic style/preference question: For strictly Python 3 code, is > there any preference for > > class MyClass: > pass > > versus the more explicit > > class MyClass(object): > pass > > ? For *purely* Python 3 code, where your audience (readers, maintainers, developers etc) are all familiar with, and expect, Python 3 semantics, not really. Maybe if you are writing introspection code which explicitly works with the class MRO or base-classes, you might prefer to be explicit. Otherwise, do whatever you feel best. For quick and dirty throw-away code, feel free to leave out the base class. If there's any chance that the code might be used in Python 2, or copied into a Python 2 module, or read by people expecting Python 2 semantics, then you ought to be explicit about the base class. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a preference of "class MyClass:" or "class MyClass(object):" for Py3?
On Fri, Jan 15, 2016 at 11:47 PM, Steven D'Aprano wrote: > > If there's any chance that the code might be used in Python 2, or copied > into a Python 2 module, or read by people expecting Python 2 semantics, > then you ought to be explicit about the base class. Hmm. I *try* to keep Python 3 at home and Python 2 at work (OT aside: Hey! I no longer have to worry about Python 2.4. I'm up to Python 2.6.4 on all platforms that I do projects for at work!). But I can imagine learning something studying at home: "Hey! What I just learned will be really useful at work! I'll just copy this class to my thumb drive and ..." Perhaps for all too easily confused boB explicit might be better than implicit? Seems I read that somewhere recently ... Thanks, Steve! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor