Re: [newbie] struggling wth tkinter
Am 07.12.13 17:52, schrieb Jean Dubois: I'm trying to go through a tutorial on tkinter which has the code below as an example. The only thing I see when running it is a little popup with Click mouse here to quit which works as expected but always shows the following error-message. However the main window which should let you enter the numbers is not shown. This is the quit error message: Traceback (most recent call last): File ./feet2meters.py, line 3, in module from tkinter import ttk ImportError: cannot import name ttk This is the code: #!/usr/bin/env python from tkinter import * from tkinter import ttk With my python2, it works to replace the import by from Tkinter import * import ttk Christian -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] struggling wth tkinter
Op zondag 8 december 2013 09:10:28 UTC+1 schreef Christian Gollwitzer: Am 07.12.13 17:52, schrieb Jean Dubois: I'm trying to go through a tutorial on tkinter which has the code below as an example. The only thing I see when running it is a little popup with Click mouse here to quit which works as expected but always shows the following error-message. However the main window which should let you enter the numbers is not shown. This is the quit error message: Traceback (most recent call last): File ./feet2meters.py, line 3, in module from tkinter import ttk ImportError: cannot import name ttk This is the code: #!/usr/bin/env python from tkinter import * from tkinter import ttk With my python2, it works to replace the import by from Tkinter import * import ttk Christian Thank you very much Christian, this solves the problem kind regards, jean -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] struggling wth tkinter
Op zondag 8 december 2013 08:49:22 UTC+1 schreef Chris Angelico: On Sun, Dec 8, 2013 at 6:40 PM, Jean Dubois jeandubois...@gmail.com wrote: coolens@antec2:~$ python3 feet2meters.py ImportError: No module named Tkinter In Python 3, the module's named tkinter instead of Tkinter. You should be able to do the exact same import but with the lower-case name, or if you need to support both: try: import tkinter as tk except ImportError: import Tkinter as tk This seems a very nice approach, but can you tell me how I should change the import-section as a whole; I tried it like here below (but that's certainly not the right way): try: import tkinter as tk except ImportError: import Tkinter as tk from tk import * import ttk thanks in advance jean -- https://mail.python.org/mailman/listinfo/python-list
Re: Is It Bug?
On Sun, Dec 8, 2013 at 2:22 AM, Roy Smith r...@panix.com wrote: There's nothing you can do with raw strings that you can't do with regular strings, but they're easier to read when you start to use backslashes. Unfortunately, there is one. A raw string cannot end with a backslash. r'a\a' 'a\\a' r'a\' File stdin, line 1 r'a\' ^ SyntaxError: EOL while scanning string literal r'\' File stdin, line 1 r'\' ^ SyntaxError: EOL while scanning string literal -- Chris “Kwpolska” Warrick http://kwpolska.tk PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense -- https://mail.python.org/mailman/listinfo/python-list
Re: Is It Bug?
On Sun, Dec 8, 2013 at 9:01 PM, Chris “Kwpolska” Warrick kwpol...@gmail.com wrote: On Sun, Dec 8, 2013 at 2:22 AM, Roy Smith r...@panix.com wrote: There's nothing you can do with raw strings that you can't do with regular strings, but they're easier to read when you start to use backslashes. Unfortunately, there is one. A raw string cannot end with a backslash. That's the other way around. There's something you can't do with a raw string that you can do with a regular. But there's nothing you can do with a raw that you can't do with a regular, as can be easily proven by looking at the repr handling - nothing will ever have a repr that's a raw string. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Is It Bug?
On Sun, Dec 8, 2013 at 9:01 PM, Chris “Kwpolska” Warrick kwpol...@gmail.com wrote: A raw string cannot end with a backslash. r'a\a' 'a\\a' r'a\' File stdin, line 1 r'a\' ^ SyntaxError: EOL while scanning string literal Incidentally, the solution to this would be to not use the backslash to escape the quote. That's what introduces the ambiguity. Instead, a raw literal could do as REXX does and double the quote to escape it. (Any whitespace and it's still concatenation as normal. I'm not advocating REXX's handling there.) rasdfqwer 'asdfqwer' If we had a new pure string that worked thus: pasdfqwer 'asdfqwer' p\b\d+\b '\\b\\d+\\b' which would be a regex matching quoted strings of digits. The only potential ambiguity would be in that closing the quote and opening another would normally revert to a regular string literal, where by this model it's still a pure string. Editor lexers would have to understand that. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sat, 07 Dec 2013 20:21:06 -0800, Mark Janssen wrote: Is it just me, or is this basically useless? class object | The most *base* type [[Terry Reedy:]] How about something like. The default top *superclass* for all Python classes. How 'bout you fools just admit that you didn't realize you've been confused this whole time? (It *is* possible isn't it?) Mr. Ewing says base has to be interpreted as an *adjective* because otherwise it would mean the BOTTOM (like the BASE of the pyramid), while Terry responds that it is the TOP (*super*class). Earlier, Steven D'Aprano wanted to argue that this distinction was irrelevant, What are you talking about? Until this very post, I haven't made any comments in this thread. but obviously it can't very well be both at once now cannit? Of course it can. To people in the southern hemisphere, the South Pole is at the top of the world and the North Pole is at the bottom. For people in the northern hemisphere, it's the opposite, with the North Pole being up and the South Pole being down. http://cdn.shopify.com/s/files/1/0071/5032/products/upside_down_world_map.png Family trees and other hierarchies, including class inheritance diagrams, have a *relative* direction not an absolute direction. We can all agree that Fred and Wilma are the parents of Pebbles, but it doesn't really matter whether we draw the family tree like this: Fred Wilma (diagrams best viewed in a fixed-width font | | like Courier, Monaco or Lucinda Typewriter) +++ | Pebbles (inheritance goes *down* the page from ancestors to descendants) or like this: Pebbles | +++ | | Fred Wilma (inheritance goes *up* the page from ancestors to descendants). What matters is the relationships between the entities, not the specific direction they are drawn in relative to some imaginary absolute space. Likewise it doesn't matter whether we draw class hierarchies from the top down or the bottom up or even sidewise: object -- int -- myint is the same as: myint -- int -- object Ironically, although it is conventional to draw the most distant ancestor at the *top* of the page, it is called the *base* or *root* of the tree. This Way Up || || || \ || / \||/ -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Is It Bug?
Mahan Marwat wrote: Why this is not working. 'Hello, World'.replace('\\', '\\') To me, Python will interpret '' to '\\'. And the replace method will replace '\\' with '\'. So, the result will be 'Hello, \World'. But it's give me 'Hello, World'. The result I want form the code is 'Hello, \World'. Let's forget about backslashes for the moment and use 'a' instead. We can replace an 'a' with an 'a' Hello, aaWorld.replace(a, a) 'Hello, aaWorld' That changes nothing. Or we can replace two 'a's with one 'a' Hello, aaWorld.replace(aa, a) 'Hello, aWorld' This does the obvious thing. Finally we can replace an 'a' with the empty string '': Hello, aaWorld.replace(a, ) 'Hello, World' This effectively removes all 'a's. Now let's replace the a with a backslash. Because the backslash has a special meaning it has to be escaped, i. e. preceded by another backslash. The examples then become Hello, World.replace(\\, \\) 'Hello, World' Hello, World.replace(, \\) 'Hello, \\World' Hello, World.replace(\\, ) 'Hello, World' While doubling of backslashes is required by Python the doubling of backslahses in the output occurs because the interactive interpreter applies repr() to the string before it is shown. You can avoid that with an explicit print statement in Python 2 or a print() function call in Python 3: print Hello, World.replace(\\, \\) Hello, \\World print Hello, World.replace(, \\) Hello, \World print Hello, World.replace(\\, ) Hello, World -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On 12/7/13 11:21 PM, Mark Janssen wrote: Is it just me, or is this basically useless? class object | The most *base* type [[Terry Reedy:]] How about something like. The default top *superclass* for all Python classes. How 'bout you fools just admit that you didn't realize you've been confused this whole time? (It *is* possible isn't it?) Mark, if you want to participate in this forum, please refrain from opening with an insult. I've tried talking with you here in the past, and got nothing but sarcastic sneers and put-downs for my trouble. I gave you the benefit of the doubt, and believed that previous contentious points (no tokens on punched cards, initializing arrays to NaN, etc) were due to misunderstandings that could be worked out. You treated me with contempt and refused to discuss the details that would have let us understand each other. I know you have a theory that all of computer science has been confused for half a century. You expounded on this before, but haven't managed to explain your point clearly, and have not convinced anyone that you have a better model than the ones we're already using. Perhaps we are confused, and you have a better idea. I don't know yet, though frankly I doubt it. I'd be glad to learn about your ideas, but you have to present them seriously, and with some humility, to get them to spread. So far, repeated attempts to get details from you have failed. Mr. Ewing says base has to be interpreted as an *adjective* because otherwise it would mean the BOTTOM (like the BASE of the pyramid), while Terry responds that it is the TOP (*super*class). Earlier, Steven D'Aprano wanted to argue that this distinction was irrelevant, but obviously it can't very well be both at once now cannit? Could-the-world-be-so-crazy-confused-and-then-shoot-the-messenger? Sadly, yes. I'm sorry you feel martyred. It's not because you bring truth to crazy-confused people. It's because you can't explain yourself, and you push people away with your style. We try hard to treat each other with respect, and I'll ask you to do the same. MarkJ Tacoma, Washington -- Ned Batchelder, http://nedbatchelder.com -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Eliminate extra variable
OK, here is the complete function code that I'm trying to improve. def MyFunc(self, originalData): self.dates = [] data = {} dateStrs = [] for i in xrange(0, len(originalData)): dateStr, freq, source = originalData[i] data[str(dateStr)] = {source: freq} dateStrs.append(dateStr) for i in xrange(0, len(dateStrs) - 1): currDateStr = str(dateStrs[i]) nextDateStr = str(dateStrs[i + 1]) self.dates.append(currDateStr) currDate = datetime.datetime.strptime(currDateStr, '%Y-%m-%d') nextDate = datetime.datetime.strptime(nextDateStr, '%Y-%m-%d') if nextDate - curDate datetime.timedelta(days=31): d = currDate + datetime.timedelta(days=1) while d nextDate: self.dates.append(d.strftime('%Y-%m-%d')) d = d + datetime.timedelta(days=1) lastDateStr = dateStrs[-1] self.dates.append(str(lastDateStr)) return data As you can see there is many conversion going on and there's unneeded dateStrs which is used just to loop thru the dictionary and get the 2 consecutive keys. This I'm trying to avoid to make this function perform faster and consume less memory. This code was written a long time ago before me and now I'm trying to improve it. I'm thinking of using the suggestion of Tim Chase which will eliminate the extra unneeded variables and will let me also eliminate a lot of back and force conversions. But if you see a better way - please share. Thank you. On Fri, Dec 6, 2013 at 5:36 PM, Igor Korot ikoro...@gmail.com wrote: OK, people, thank you everybody for the input. Here is the more explanation that I think is in order: The originalData comes from either SQLite DB or mySQL DB. Since first uses strings and second uses datetime I am using str() to make the data consistent. Now the query is this: SELECT date, freq, value FROM my_table ORDER BY date; and so I do know that the originalData is already presorted (ordered). So sorting is not a problem here. Now what I'm looking for here is check whether the time difference between the currDateStr and nextDateStr is 30 days. If its do some calculation and pass the dictionary with dates as strings to the next function. That function is inside wxPython (GUI) which will do plotting. In the plot function the dates will be used as the labels for the x-axis. So this is another reason to keep dates as strings. I hope I made it a little clear and hopefully someone will give me Python example of how do I simplify this code to eliminate un-needed variables. Thank you. On Fri, Dec 6, 2013 at 5:19 PM, Igor Korot ikoro...@gmail.com wrote: Hi, Gary, On Fri, Dec 6, 2013 at 3:28 PM, Gary Herron gary.her...@islandtraining.com wrote: On 12/06/2013 11:37 AM, Igor Korot wrote: Hi, ALL, I have following code: def MyFunc(self, originalData): data = {} dateStrs = [] for i in xrange(0, len(originalData)): dateStr, freq, source = originalData[i] data[str(dateStr)] = {source: freq} dateStrs.append(dateStr) for i in xrange(0, len(dateStrs) - 1): currDateStr = str(dateStrs[i]) nextDateStrs = str(dateStrs[i + 1]) It seems very strange that I need the dateStrs list just for the purpose of looping thru the dictionary keys. Can I get rid of the dateStrs variable? Thank you. You want to build a list, but you don't want to give that list a name? Why not? And how would you refer to that list in the second loop if it didn't have a name? And concerning that second loop: What are you trying to do there? It looks like a complete waste of time. In fact, with what you've shown us, you can eliminate the variable dateStrs, and both loops and be no worse off. Perhaps there is more to your code than you've shown to us ... What I want here is to do something like this: def MyFunc(self, originalData): data = {} for i in xrange(0, len(originalData)): dateStr, freq, source = originalData[i] data[str(dateStr)] = {source: freq} for i in xrange(0, len(data) - 1): currDateStr = str(data[i].key()) // I need a syntax here nextDateStrs = str(data[i + 1].key())// I need a syntax here Thank you. Gary Herron -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Origin of eval()-ing in separate namespace object
By which languages(s) Python was inspired to support evaluating expressions and executing statements in a separate “namespace” object? This syntax: eval(expression,globals) or exec(code,globals) What is the origin of the functionality provided by the globals argument? -- https://mail.python.org/mailman/listinfo/python-list
Re: Origin of eval()-ing in separate namespace object
On Sunday, December 8, 2013 4:05:54 PM UTC+5:30, Kalinni Gorzkis wrote: By which languages(s) Python was inspired to support evaluating expressions and executing statements in a separate “namespace” object? This syntax: eval(expression,globals) or exec(code,globals) What is the origin of the functionality provided by the globals argument? Been here since the days of scheme at least http://docs.racket-lang.org/guide/eval.html#%28part._namespaces%29 For the record lisp was conceptualized in the late 50s and implemented by 1960. By the 80s it was widely regarded as the premier AI language but it was also clear to users that the scoping rules were terribly wrong. So a number of the then lisps coalesced and re-separated into 2 major dialects -- scheme and common lisp. I expect it -- 2 argument eval -- goes all the way back to the earliest lisp but Ive not access to the history. -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
Tim Chase wrote: On 2013-12-06 11:37, Igor Korot wrote: def MyFunc(self, originalData): data = {} for i in xrange(0, len(originalData)): dateStr, freq, source = originalData[i] data[str(dateStr)] = {source: freq} this can be more cleanly/pythonically written as def my_func(self, original_data): for date, freq, source in original_data data[str(date)] = {source: freq} or even just data = dict( (str(date), {source: freq}) for date, freq, source in original_data ) or even just data = {str(date): {source: freq} for date, freq, source in original_data} But do you really need a dict with a single key? And is it even correct? If a date occurs twice only the last source:freq pair is kept. Without knowing the context the humble data = {} for date, freq, source in original_data: source_to_freq = data.setdefault(date, {}) if source in source_to_freq: raise ValueError( Multiple frequencies for one source not supported) source_to_freq[source] = freq appears so much more plausible... You're calling it a dateStr, which suggests that it's already a string, so I'm not sure why you're str()'ing it. So I'd either just call it date, or skip the str(date) bit if it's already a string. That said, do you even need to convert it to a string (as datetime.date objects can be used as keys in dictionaries)? for i in xrange(0, len(dateStrs) - 1): currDateStr = str(dateStrs[i]) nextDateStrs = str(dateStrs[i + 1]) It seems very strange that I need the dateStrs list just for the purpose of looping thru the dictionary keys. Can I get rid of the dateStrs variable? Your code isn't actually using the data-dict at this point. If you were doing something with it, it might help to know what you want to do. Well, you can iterate over the original data, zipping them together: for (cur, _, _), (next, _, _) in zip( original_data[:-1], original_data[1:] ): do_something(cur, next) This reminds me that I am a proponent of small dumb helper functions ;) I find def sliding_window(items): a, b = itertools.tee(items) next(b, None) return zip(a, b) dates = (date for date, _freq, _source in original_data) for from_date, to_date in sliding_window(dates): do_something(from_date, to_date) much more accessible. Plus, I can apply arbitrary improvements to the sliding_window() implementation or switch to a library version of that function without fear of messing things up. Likewise, should original_data become a sequence of namedtuples it is straightforward to propagate this change with dates = (item.date for item in original_data) If your purpose for the data dict is to merely look up stats from the next one, the whole batch of your original code can be replaced with: for ( (cur_dt, cur_freq, cur_source), (next_dt, next_freq, next_source) ) in zip(original_data[:-1], original_data[1:]): # might need to do str(cur_dt) and str(next_dt) instead? do_things_with(cur_dt, cur_freq, cur_source, next_dt, next_freq, next_source) That eliminates the dict *and* the extra variable name. :-) Smileys are overused ;) Anyway, with namedtuples this ... would become for cur_item, next_item in zip(original_data, original_data[1:]): do_things_with(cur_item, next_item) Note that there's no need to slice the first argument as zip() ignores extra items. -- https://mail.python.org/mailman/listinfo/python-list
Re: Centring text in a rect in PyGame?
On 07/12/2013 12:41, Eamonn Rea wrote: First of all. I’d like to say I have no idea how these ‘mailing lists’ work, so I don’t know if this’ll come through right, but we’ll see I guess :-) I’m coming from the Google Group comp.lang.python, and was suggested to use this instead. Assuming attachments and images work, you should have an image of my code’s result and the attached code files. [... snip HTML text, images attached code files ...] Hi Eamonn. I'm one of the list owners so this reply is about list etiquette rather than the pygame issue you're having :) I'm taking advantage of your self-professed ignorance to make some general points which other might find helpful. I hope you don't mind. First: python-list mirrors comp.lang.python and vice versa (either via nntp or via Google Groups). However GG has, for the last while, been responsible for disrupting the text it passes through -- extra line spaces etc. -- with the result that mailing list or newsgroup readers find it very frustrating to read GG-formatted versions of messages. I expect that's why you were pointed towards the mailing list. It's also possible to access via comp.lang.python on Usenet; or comp.python.general on gmane. In general, while it's technically possible to post screenshots and to attach code files to the mailing list, it's not encouraged. At least partly that's because those who read via Usenet probably won't see them. Even those of us reading via mailing list may find it harder to read your post if it's spread out among multiple files. And to complete the list, you should post in plain text rather than HTML or rich-text. For much the same reasons. In short, the mailing list and the newsgroup it mirrors are best treated as plain text only. Another reason for discouraging screen / code dumps is that the very fact of narrowing down a small, repeatable segment of code with which to illustrate the issue can actually lead to your seeing the problem anyway! Even if it doesn't it's *much* easier for the other list members to comprehend / try out a small code segment than to read through your whole code. If push comes to shove, you can post code on a pastebin service -- but that is frowned upon by some, both because of the need to link to an unknown URL and because the code you post may not be there in 2 years time when someone having the same issue is following this thread to find help! TJG -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] struggling wth tkinter
On Sat, 7 Dec 2013 23:45:06 -0800 (PST), Jean Dubois jeandubois...@gmail.com wrote: This is what I get: Traceback (most recent call last): File ./feet2meters.py, line 2, in module from tkinter import * File /home/jean/tkinter.py, line 2, in module import Tkinter as tk ImportError: No module named Tkinter Regardless of your other fixes, you should rename the bogus file: /home/jean/tkinter.py You very seldom want to have files that can shadow system modules. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] struggling wth tkinter
This is what I get: Traceback (most recent call last): File ./feet2meters.py, line 2, in module from tkinter import * File /home/jean/tkinter.py, line 2, in module import Tkinter as tk ImportError: No module named Tkinter From your original post I only changed the she-bang line from python to python3 #!/usr/bin/env python3 and the import lines remained as you originally posted which are appropriate for python3 from tkinter import * from tkinter import ttk The traceback above shows an import statement that is different from the one you originally posted which would be ok in python2 but not python3 import Tkinter as tk -- Stanley C. Kitching Human Being Phoenix, Arizona -- https://mail.python.org/mailman/listinfo/python-list
Re: Origin of eval()-ing in separate namespace object
rusi writes: On Sunday, December 8, 2013 4:05:54 PM UTC+5:30, Kalinni Gorzkis wrote: By which languages(s) Python was inspired to support evaluating expressions and executing statements in a separate namespace object? This syntax: eval(expression,globals) or exec(code,globals) What is the origin of the functionality provided by the globals argument? Been here since the days of scheme at least http://docs.racket-lang.org/guide/eval.html#%28part._namespaces%29 For the record lisp was conceptualized in the late 50s and implemented by 1960. By the 80s it was widely regarded as the premier AI language but it was also clear to users that the scoping rules were terribly wrong. So a number of the then lisps coalesced and re-separated into 2 major dialects -- scheme and common lisp. I expect it -- 2 argument eval -- goes all the way back to the earliest lisp but Ive not access to the history. Yes. From p. 13 of LISP 1.5 Programmer's Manual (the preface is dated in 1962): # _evalquote_ is defined by using two main functions, called _eval_ # and _apply_. _apply_ handles a function and its arguments, while # _eval_ handles forms. Each of these functions also has another # argument that is used as an association list for storing the values # of bound variables and function names. That association list is the namespace. _eval_ and _apply_ pass it around and extend it as they call each other to evalute code. So it seems that at least the idea of an explicit namespace argument was there from the start. Mistakes related to the original dynamic scoping continued to be made. -- https://mail.python.org/mailman/listinfo/python-list
Re: Centring text in a rect in PyGame?
On Sunday, December 8, 2013 7:36:04 PM UTC+5:30, Tim Golden wrote: On 07/12/2013 12:41, Eamonn Rea wrote: First of all. Id like to say I have no idea how these mailing lists work, so I dont know if this'll come through right, but we'll see I guess :-) I'm coming from the Google Group comp.lang.python, and was suggested to use this instead. Assuming attachments and images work, you should have an image of my code�s result and the attached code files. Hi Eamonn There are some new instructions/suggestions to make google groups easier on you (and other readers!) https://wiki.python.org/moin/GoogleGroupsPython If you try them and they work (or even if they dont!) please let me know. Particularly note the new section at the end https://wiki.python.org/moin/GoogleGroupsPython#Automatic_correction_.28EXPERIMENTAL.29 -- https://mail.python.org/mailman/listinfo/python-list
Re: Centring text in a rect in PyGame?
On 07/12/2013 12:41, Eamonn Rea wrote: Anyway, I have a problem. In my game, I want to draw a button. I’ve gotten the button to draw fine, but I want some text on the button. I’ve gotten the text to draw, but I can’t get it to centre into the button. Here’s the code I’ve used: *self.surface.blit(self.button_text, (self.width / 2 - self.button_text.get_width() / 2, self.height / 2 - self.button_text.get_height() / 2))* Side-stepping your actual code, here's a handy thing in pygame. You can center one rect on another to achieve the same effect without bothering with the (x - y) / 2 stuff. import pygame pygame.init() # # For demo purposes, the button is the whole window # button = pygame.display.set_mode((400, 320)) # # Create 12-point text in white saying Hello, World! # font = pygame.font.Font(pygame.font.get_default_font(), 12) text = font.render(Hello, World!, True, (0xff, 0xff, 0xff)) # # Use the text's rect to get width / height # Then center that rect on the target surface # text_rect = text.get_rect() text_rect.center = button.get_rect().center button.blit(text, text_rect) pygame.display.flip() TJG -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] struggling wth tkinter
Op zondag 8 december 2013 15:16:25 UTC+1 schreef Dave Angel: On Sat, 7 Dec 2013 23:45:06 -0800 (PST), Jean Dubois jeandubois...@gmail.com wrote: This is what I get: Traceback (most recent call last): File ./feet2meters.py, line 2, in module from tkinter import * File /home/jean/tkinter.py, line 2, in module import Tkinter as tk ImportError: No module named Tkinter Regardless of your other fixes, you should rename the bogus file: /home/jean/tkinter.py You very seldom want to have files that can shadow system modules. -- DaveA Thank you Dave, this made it work under python3 too. I also had to remove tkinter.pyc kind regards, jean -- https://mail.python.org/mailman/listinfo/python-list
Re: Origin of eval()-ing in separate namespace object
On Sunday, December 8, 2013 8:09:39 PM UTC+5:30, Jussi Piitulainen wrote: rusi writes: On Sunday, December 8, 2013 4:05:54 PM UTC+5:30, Kalinni Gorzkis wrote: By which languages(s) Python was inspired to support evaluating expressions and executing statements in a separate namespace object? This syntax: eval(expression,globals) or exec(code,globals) What is the origin of the functionality provided by the globals argument? Been here since the days of scheme at least http://docs.racket-lang.org/guide/eval.html#%28part._namespaces%29 For the record lisp was conceptualized in the late 50s and implemented by 1960. By the 80s it was widely regarded as the premier AI language but it was also clear to users that the scoping rules were terribly wrong. So a number of the then lisps coalesced and re-separated into 2 major dialects -- scheme and common lisp. I expect it -- 2 argument eval -- goes all the way back to the earliest lisp but Ive not access to the history. Yes. From p. 13 of LISP 1.5 Programmer's Manual (the preface is dated in 1962): # _evalquote_ is defined by using two main functions, called _eval_ # and _apply_. _apply_ handles a function and its arguments, while # _eval_ handles forms. Each of these functions also has another # argument that is used as an association list for storing the values # of bound variables and function names. Heh – I am nostalgia-fied! Wrote a Lisp interpreter as a student degree project in 1986. Tried to use the Lisp 1.5 manual then but it was too archaic for me to understand. So mostly chewed on the UCI Lisp manual. Took me some years to understand that dynamic scoping was not my mistake but Lisp's!! -- https://mail.python.org/mailman/listinfo/python-list
Re: ASCII and Unicode
On Saturday, December 7, 2013 9:35:34 PM UTC+5:30, giacomo boffi wrote: Steven D'Aprano writes: Ironically, your post was not Unicode. [...] Your post was sent using a legacy encoding, Windows-1252, also known as CP-1252 i access rusi's post using a NNTP server, and in his post i see Content-Type: text/plain; charset=UTF-8 is it possible that what you see is an artifact of the gateway? Thanks for checking that! -- https://mail.python.org/mailman/listinfo/python-list
Re: ASCII and Unicode
On Sat, 07 Dec 2013 17:05:34 +0100, giacomo boffi wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes: Ironically, your post was not Unicode. [...] Your post was sent using a legacy encoding, Windows-1252, also known as CP-1252 i access rusi's post using a NNTP server, and in his post i see Content-Type: text/plain; charset=UTF-8 But *which post* are you looking at? I have just looked at three posts from him: Rusi's original post, where he used the ellipsis characters: Subject: Re: Managing Google Groups headaches Date: Thu, 5 Dec 2013 23:13:54 -0800 (PST) Content-Type: text/plain; charset=windows-1252 Then his reply to me: Subject: Re: ASCII and Unicode [was Re: Managing Google Groups headaches] Date: Fri, 6 Dec 2013 18:33:39 -0800 (PST) Content-Type: text/plain; charset=UTF-8 And finally, his reply to you: Subject: Re: ASCII and Unicode Date: Sun, 8 Dec 2013 08:41:10 -0800 (PST) Content-Type: text/plain; charset=ISO-8859-1 It seems to me that whatever client he is using to post (I believe it is Google Groups web interface?) varies the encoding depending on what characters are included in his post. is it possible that what you see is an artifact of the gateway? I doubt it. Unfortunately the email mailing list archive doesn't display all the email headers, but for the record here is his original post as seen by the email mailing list: https://mail.python.org/pipermail/python-list/2013-December/661782.html If you view source, you'll see that Mailman (the mailing list software) sets the webpage encoding to US-ASCII and encodes the ellipses to #8230, which is a perfectly reasonable thing for a web page to do. So we can be confident that when Mailman saw Rusi's post, it was able to correctly decode the message and see ellipses. Although I think that (probably) Google Groups is being stupid by varying the charset (why not just use UTF-8 always?), at least it is setting the charset correctly. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: ASCII and Unicode
On Sunday, December 8, 2013 10:52:34 PM UTC+5:30, Steven D'Aprano wrote: On Sat, 07 Dec 2013 17:05:34 +0100, giacomo boffi wrote: Steven D'Aprano writes: Ironically, your post was not Unicode. [...] Your post was sent using a legacy encoding, Windows-1252, also known as CP-1252 i access rusi's post using a NNTP server, and in his post i see Content-Type: text/plain; charset=UTF-8 But *which post* are you looking at? I have just looked at three posts from him: Rusi's original post, where he used the ellipsis characters: Subject: Re: Managing Google Groups headaches Date: Thu, 5 Dec 2013 23:13:54 -0800 (PST) Content-Type: text/plain; charset=windows-1252 Then his reply to me: Subject: Re: ASCII and Unicode [was Re: Managing Google Groups headaches] Date: Fri, 6 Dec 2013 18:33:39 -0800 (PST) Content-Type: text/plain; charset=UTF-8 And finally, his reply to you: Subject: Re: ASCII and Unicode Date: Sun, 8 Dec 2013 08:41:10 -0800 (PST) Content-Type: text/plain; charset=ISO-8859-1 It seems to me that whatever client he is using to post (I believe it is Google Groups web interface?) varies the encoding depending on what characters are included in his post. is it possible that what you see is an artifact of the gateway? I doubt it. Unfortunately the email mailing list archive doesn't display all the email headers, but for the record here is his original post as seen by the email mailing list: https://mail.python.org/pipermail/python-list/2013-December/661782.html If you view source, you'll see that Mailman (the mailing list software) sets the webpage encoding to US-ASCII and encodes the ellipses to #8230, which is a perfectly reasonable thing for a web page to do. So we can be confident that when Mailman saw Rusi's post, it was able to correctly decode the message and see ellipses. Although I think that (probably) Google Groups is being stupid by varying the charset (why not just use UTF-8 always?), at least it is setting the charset correctly. I think GG is being being sweet and affectionate and delectable enough that a in the footer will keep it stuck at UTF-8 you think ?? :-) -- https://mail.python.org/mailman/listinfo/python-list
python programming help
i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
Le 08.12.2013 18:59, rafaella...@gmail.com a écrit : i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help ageDict = { 'john':42, 'jane':36, 'paul':42 } peopleWithAge = lambda age: [ name for name in ageDict if ageDict[name]==age] -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Sunday, December 8, 2013 6:07:47 PM UTC, YBM wrote: Le 08.12.2013 18:59, rafaella...@gmail.com a �crit : i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help ageDict = { 'john':42, 'jane':36, 'paul':42 } peopleWithAge = lambda age: [ name for name in ageDict if ageDict[name]==age] sorry but i'm new to python ;p 1. it has to be in a form of a function called people and 2. how this code takes in an age and returns the names? -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
Le 08.12.2013 19:14, rafaella...@gmail.com a écrit : On Sunday, December 8, 2013 6:07:47 PM UTC, YBM wrote: Le 08.12.2013 18:59, rafaella...@gmail.com a �crit : i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help ageDict = { 'john':42, 'jane':36, 'paul':42 } peopleWithAge = lambda age: [ name for name in ageDict if ageDict[name]==age] sorry but i'm new to python ;p 1. it has to be in a form of a function called people and 2. how this code takes in an age and returns the names? ageDict = { 'john':42, 'jane':36, 'paul':42 } people = lambda age: [ name for name in ageDict if ... ageDict[name]==age] people(42) ['paul', 'john'] -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
In article 264c1144-5d04-4ad0-aa32-f4e6770d2...@googlegroups.com, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help Homework problem? In any case, this is a classic example of a real-life problem, and thus worth exploring. The general case is you have a many-to-one mapping and you want to find the inverse one-to-many map. I'm assuming when you say, a dictionary with names and ages for each name, you mean the names are the keys and the ages are the values. That would also imply that the names are unique; that's a poor assumption for real data sets, but let's assume that's the case here. So, we're going to take your original dictionary and create a new one where the keys are the ages, and the values are lists of names. That's pretty straight forward. Here's the most brute-force way (which is a good place to start): d2 = {} for name, age in d1.items(): if age not in d2: d2[age] = [] d2[age].append(name) Work through that code in your head to convince yourself that you understand what's going on. This is such a common pattern, Python has a neat tool to make this easier. It's called a defaultdict. Bascially, this is a dictionary which has built into it the if key doesn't exist, initialize something logic. It works like this: from collections import defaultdict d2 = defaultdict(list) for name, age in d1.items(): d2[age].append(name) The defaultdict(list) creates one of these and tells it that the initialize something part should be create an empty list. It's hugely convenient and used all the time. -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 12/8/2013 12:59 PM, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help Welcome to the python list. Thanks for posting a question. If you were hoping for one of us to write the program for you ... well that's not what we do on this list. Please post the code you have so far and tell us exactly where you need help. Also tell us what version of Python, what OS, and what you use to write and run Python programs. -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 12/08/2013 09:59 AM, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help This looks like homework for a beginning programming class. Correct? We like helping people use Python, and we like helping people learn Python, but neither of those purposes are served by us *doing* your homework for you. Please, you try to solve the problem, and when you get stuck, show us your code, and ask a specific question. Hint: You will almost certainly need a loop (through the dictionary entries), an 'if' conditional to test for the age matching the given age, and a print, Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 08/12/2013 18:14, rafaella...@gmail.com wrote: On Sunday, December 8, 2013 6:07:47 PM UTC, YBM wrote: Le 08.12.2013 18:59, rafaella...@gmail.com a �crit : i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help ageDict = { 'john':42, 'jane':36, 'paul':42 } peopleWithAge = lambda age: [ name for name in ageDict if ageDict[name]==age] sorry but i'm new to python ;p 1. it has to be in a form of a function called people and 2. how this code takes in an age and returns the names? I'm awfully sorry but I'm not doing your homework for you :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Sunday, December 8, 2013 6:27:34 PM UTC, bob gailer wrote: On 12/8/2013 12:59 PM, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help Welcome to the python list. Thanks for posting a question. If you were hoping for one of us to write the program for you ... well that's not what we do on this list. Please post the code you have so far and tell us exactly where you need help. Also tell us what version of Python, what OS, and what you use to write and run Python programs. name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] dic={} def combine_lists(name,age): for i in range(len(name)): dic[name[i]]= age[i] combine_lists(name,age) print dic def people(age): people=lambda age: [name for name in dic if dic[name]==age] people(20) this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Sunday, December 8, 2013 6:32:31 PM UTC, rafae...@gmail.com wrote: On Sunday, December 8, 2013 6:27:34 PM UTC, bob gailer wrote: On 12/8/2013 12:59 PM, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help Welcome to the python list. Thanks for posting a question. If you were hoping for one of us to write the program for you ... well that's not what we do on this list. Please post the code you have so far and tell us exactly where you need help. Also tell us what version of Python, what OS, and what you use to write and run Python programs. name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] dic={} def combine_lists(name,age): for i in range(len(name)): dic[name[i]]= age[i] combine_lists(name,age) print dic def people(age): people=lambda age: [name for name in dic if dic[name]==age] people(20) this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result and I'm sorry but this is the first time i ask for help in a forum and i just didn't know how it works. I'm not looking for someone to do my homework i just need someone to help me with my code :) -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
On 2013-12-08 15:04, Peter Otten wrote: data = dict( (str(date), {source: freq}) for date, freq, source in original_data ) or even just data = {str(date): {source: freq} for date, freq, source in original_data} I maintain enough pre-2.7 code that I tend to eschew dict-comprehensions for the time being. I like them as a language addition, but can't use them yet in most of the code-bases with which I work. To the OP, if you don't have to support pre-2.7 code, then this is a tidier way to go. But do you really need a dict with a single key? And is it even correct? If a date occurs twice only the last source:freq pair is kept. Without knowing the context the humble data = {} for date, freq, source in original_data: source_to_freq = data.setdefault(date, {}) if source in source_to_freq: raise ValueError( Multiple frequencies for one source not supported) source_to_freq[source] = freq appears so much more plausible... The OP's code didn't do any such sanity-checking so I made the assumption that the data came in clean. I know better than to trust incoming data (even my own) in my own code, but... (followup to the OP's reply elsewhere in the thread coming shortly) -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
On 2013-12-07 23:14, Igor Korot wrote: def MyFunc(self, originalData): self.dates = [] data = {} dateStrs = [] for i in xrange(0, len(originalData)): dateStr, freq, source = originalData[i] data[str(dateStr)] = {source: freq} dateStrs.append(dateStr) for i in xrange(0, len(dateStrs) - 1): currDateStr = str(dateStrs[i]) nextDateStr = str(dateStrs[i + 1]) self.dates.append(currDateStr) currDate = datetime.datetime.strptime(currDateStr, '%Y-%m-%d') nextDate = datetime.datetime.strptime(nextDateStr, '%Y-%m-%d') if nextDate - curDate datetime.timedelta(days=31): d = currDate + datetime.timedelta(days=1) while d nextDate: self.dates.append(d.strftime('%Y-%m-%d')) d = d + datetime.timedelta(days=1) lastDateStr = dateStrs[-1] self.dates.append(str(lastDateStr)) return data It would help to know what you want this function to accomplish: MyFunc isn't exactly descriptive. From what I gather by reading it, you want it to do two things: - append each date in the range from originalData[0] through originalData[-1] to self.dates every time this function is called (which means that multiple calls to this will grow self.dates every time) - if there's less than 31 days between N and N+1, also append all the dates in between (this seems weird, but okay). Again, every time this function is called. - return a dictionary that maps dates in the input-data to the associated source:freq dictionary. It's hard to tell what you intend to do with these results. If you just intend to iterate over them once, asking for associated data, you could even create a generator that yields the date along with either None or the associated data. See below for that. Alternatively, you can return both the dict-mapping and the date-list from the function: def f(...): return (the_dict, the_list) a_dict, a_list = f(...) That would prevent repeated mutation of self.dates As you can see there is many conversion going on and there's unneeded dateStrs which is used just to loop thru the dictionary and get the 2 consecutive keys. The final snippet of code that I provided handles this pretty nicely by zipping up the staggered lists and iterating over them while unpacking them into sensible variable names. Unless you have a need to operate on the dates as string, I'd just keep them as dates throughout the code and only turn them into strings upon output. But if you see a better way - please share. I'd likely incorporate Peter's sliding_window() suggestion and do something like the following (I commented out using a tuple for the values, but using a tuple/namedtuple might make more sense) import itertools def sliding_window(i): a, b = itertools.tee(i) next(b) return itertools.izip(a, b) def some_descriptive_function_name(self, original_data): # construct these once-per-call rather than every loop # or even move them out to module-scope ONE_DAY = datetime.timedelta(days=1) MONTHISH = datetime.timedelta(days=31) for ( (cur_dt, cur_freq, cur_source), (next_dt, next_freq, next_source) ) in sliding_window(original_data): info = {cur_source: cur_freq} # info = (cur_source, cur_freq) yield cur_dt, info if next_dt - cur_dt MONTHISH: d = cur_dt + ONE_DAY while d next_dt: yield d, None d += ONE_DAY info = {next_source: next_freq} # info = (next_source, next_freq) yield next_dt, info which can then be used with for dt, info in self.some_descriptive_function_name(data): # dates should be returned in the same sequence # as your original logic if info is None: do_something_when_no_info(dt) else: do_something_with_dt_and_info(dt, info) If you need to iterate over the data multiple times, you can just do tmp = list(self.some_descriptive_function_name(data)) do_first(tmp) do_second(tmp) -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Sun, Dec 8, 2013 at 10:32 AM, rafaella...@gmail.com wrote: On Sunday, December 8, 2013 6:27:34 PM UTC, bob gailer wrote: On 12/8/2013 12:59 PM, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help Welcome to the python list. Thanks for posting a question. If you were hoping for one of us to write the program for you ... well that's not what we do on this list. Please post the code you have so far and tell us exactly where you need help. Also tell us what version of Python, what OS, and what you use to write and run Python programs. name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] dic={} def combine_lists(name,age): for i in range(len(name)): dic[name[i]]= age[i] combine_lists(name,age) print dic def people(age): people=lambda age: [name for name in dic if dic[name]==age] people(20) this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result To return a value from a function, you need to use the return statement with the value you want to pass back out. You're not doing that here. Also, you're using a lot of shorthand stuff that you should probably avoid until you're more comfortable with the language * Lambda is shorthand for a function. foo = lambda bar : bar + 2 is the same thing as the function def foo(bar) : return bar + 2 * a list comprehension is short-hand for a loop. spam = [foo for foo in bar if baz(foo)] is the same thing as spam = [] for foo in bar : if baz(foo) : spam.append(foo) You don't need a lambda here- just call the code that you need to call directly. -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Sunday, December 8, 2013 6:52:12 PM UTC, Benjamin Kaplan wrote: On Sun, Dec 8, 2013 at 10:32 AM, rafaella...@gmail.com wrote: On Sunday, December 8, 2013 6:27:34 PM UTC, bob gailer wrote: On 12/8/2013 12:59 PM, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help Welcome to the python list. Thanks for posting a question. If you were hoping for one of us to write the program for you ... well that's not what we do on this list. Please post the code you have so far and tell us exactly where you need help. Also tell us what version of Python, what OS, and what you use to write and run Python programs. name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] dic={} def combine_lists(name,age): for i in range(len(name)): dic[name[i]]= age[i] combine_lists(name,age) print dic def people(age): people=lambda age: [name for name in dic if dic[name]==age] people(20) this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result To return a value from a function, you need to use the return statement with the value you want to pass back out. You're not doing that here. Also, you're using a lot of shorthand stuff that you should probably avoid until you're more comfortable with the language * Lambda is shorthand for a function. foo = lambda bar : bar + 2 is the same thing as the function def foo(bar) : return bar + 2 * a list comprehension is short-hand for a loop. spam = [foo for foo in bar if baz(foo)] is the same thing as spam = [] for foo in bar : if baz(foo) : spam.append(foo) You don't need a lambda here- just call the code that you need to call directly. i get it, thanks a lot i wrote a different one and it works def people(age): people=[name for name in dic if dic[name]==age] print(people) people(20) i have one last question it asks me to test my program function by running these lines: print ’Dan’ in people(18) and ’Cathy’ in people(18) print ’Ed’ in people(19) and ’Helen’ in people(19) and\ ’Irene’ in people(19) and ’Jack’ in people(19) and ’Larry’in people(19) print ’Alice’ in people(20) and ’Frank’ in people(20) and ’Gary’ in people(20) print people(21) == [’Bob’] print people(22) == [’Kelly’] print people(23) == [] but when i wrote these lines it returns me an error Traceback (most recent call last): File /Users/rafaellasavva/Desktop/people.py, line 19, in module print 'Dan' in people(18) and 'Cathy' in people(18) TypeError: argument of type 'NoneType' is not utterable do you know what it might be wrong? -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
On 08/12/2013 18:58, Tim Chase wrote: On 2013-12-07 23:14, Igor Korot wrote: [big snip] Whenever I need date manipulations I always reach out to this http://labix.org/python-dateutil -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Mon, Dec 9, 2013 at 6:06 AM, rafaella...@gmail.com wrote: but when i wrote these lines it returns me an error Traceback (most recent call last): File /Users/rafaellasavva/Desktop/people.py, line 19, in module print 'Dan' in people(18) and 'Cathy' in people(18) TypeError: argument of type 'NoneType' is not utterable do you know what it might be wrong? Hehe. The first thing that's wrong is that you're retyping the error instead of copying and pasting it. The problem is actually that it's not *iterable* here. And the reason for that is that you're printing the result instead of returning it, as has been mentioned by a few people. Also, your posts are acquiring the slimy stain of Google Groups, which makes them rather distasteful. All your replies are getting double-spaced, among other problems. Please consider switching to an alternative newsgroup reader, or subscribing to the mailing list: https://mail.python.org/mailman/listinfo/python-list The content is the same, but it comes by email instead of netnews. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 08/12/2013 19:06, rafaella...@gmail.com wrote: i get it, thanks a lot i wrote a different one and it works def people(age): people=[name for name in dic if dic[name]==age] print(people) people(20) i have one last question it asks me to test my program function by running these lines: print ’Dan’ in people(18) and ’Cathy’ in people(18) print ’Ed’ in people(19) and ’Helen’ in people(19) and\ ’Irene’ in people(19) and ’Jack’ in people(19) and ’Larry’in people(19) print ’Alice’ in people(20) and ’Frank’ in people(20) and ’Gary’ in people(20) print people(21) == [’Bob’] print people(22) == [’Kelly’] print people(23) == [] but when i wrote these lines it returns me an error Traceback (most recent call last): File /Users/rafaellasavva/Desktop/people.py, line 19, in module print 'Dan' in people(18) and 'Cathy' in people(18) TypeError: argument of type 'NoneType' is not utterable do you know what it might be wrong? You've typed up the error message instead of using cut and paste, which is why it says utterable instead of iterable? :) Seriously, it's already been pointed out that your people function needs a return statement. Without it, the default returned is always None. Would you also please read and action this https://wiki.python.org/moin/GoogleGroupsPython as it prevents us seeing huge numbers of unwanted newlines which some find extremely irritating. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
On 2013-12-08 19:10, Mark Lawrence wrote: On 08/12/2013 18:58, Tim Chase wrote: On 2013-12-07 23:14, Igor Korot wrote: [big snip] Whenever I need date manipulations I always reach out to this http://labix.org/python-dateutil But based on the OP's repeated transformations from date-to-string and back again, what do you reach for when you want to transform things *needlessly*? I recommend the delete key and some healthy refactoring. :-) -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Sunday, December 8, 2013 10:32:31 AM UTC-8, rafae...@gmail.com wrote: [snip] def people(age): people=lambda age: [name for name in dic if dic[name]==age] people(20) [snip] this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. Well then, don't use it! It's clear that you are new, and at least you have posted some code now, so let me try to help. and this code doesn't give me any result Right, for TWO reasons. First problem: if your function does not end with a statement like return people, the function returns a special Python object called None. Now, if it were me, I would not wrap the calculation of your people list inside a people function for such a short program. But this is apparently a requirement of your assignment. My guess is, in the future, you will write a program that calls the people function multiple times. The lambda word has to do with creating something called an anonymous one-line function. You don't need that here. It's more advanced Python. What you want to do is compute and, importantly, return a list calculated from your dictionary. That is accomplished by this expression: [name for name in dic if dic[name]==age] This is called a list comprehension. Do you understand what this does? It's fairly advanced. I don't teach list comprehensions to my Python students for the first several lessons. So, now that you have created the list, let's make sure that Python doesn't lose it. Let's assign a NAME to it. By the way, it's probably not good form to use the same name for a function and any of its internal variables. Pick a different name for your list: for example, p. Then, return p from your function to your main program. My suggested rewrite of your function would be: def people(age): p = [name for name in dic if dic[name]==age] return p The truth is that you can cut this down by even one more line. This function doesn't need to hold on to the result after it is done returning it, but the computation of the result can be accomplished in one line. Therefore this will also work: def people(age): return [name for name in dic if dic[name]==age] OK, that takes care of Problem 1. Second problem: you call the people function with your statement people(20), but you don't do anything with the output. Once you fix the people function by providing a proper return statement, what does the main program do with the output of the function? Right now, it just throws it away. One solution to the problem is to make sure that the function's output gets a name. Try: result = people(20) Now, what do you want to do with result? I will wait to see your answer on that one before I intervene again. -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
On 08/12/2013 19:23, Tim Chase wrote: On 2013-12-08 19:10, Mark Lawrence wrote: On 08/12/2013 18:58, Tim Chase wrote: On 2013-12-07 23:14, Igor Korot wrote: [big snip] Whenever I need date manipulations I always reach out to this http://labix.org/python-dateutil But based on the OP's repeated transformations from date-to-string and back again, what do you reach for when you want to transform things *needlessly*? I recommend the delete key and some healthy refactoring. :-) -tkc Painkillers :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Domino, a Python PaaS for data science
Hi list, This may be of interest: Domino, a Python PaaS for data science: http://jugad2.blogspot.in/2013/12/domino-paas-for-data-science.html - Vasudev Ram Software training and consulting Python, Linux, C, open source, databases ... www.dancingbison.com jugad2.blogspot.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
In article mailman.3738.1386529877.18130.python-l...@python.org, Mark Lawrence breamore...@yahoo.co.uk wrote: On 08/12/2013 18:58, Tim Chase wrote: On 2013-12-07 23:14, Igor Korot wrote: [big snip] Whenever I need date manipulations I always reach out to this http://labix.org/python-dateutil The problem with dateutil is it's dog slow. Sure, I use it too, when convenience is more important than performance, but have you ever looked at the code for dateutil.parser.parse()? It's worth reading, just for fun. -- https://mail.python.org/mailman/listinfo/python-list
Re: ASCII and Unicode
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes: On Sat, 07 Dec 2013 17:05:34 +0100, giacomo boffi wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes: Ironically, your post was not Unicode. [...] Your post was sent using a legacy encoding, Windows-1252, also known as CP-1252 i access rusi's post using a NNTP server, and in his post i see Content-Type: text/plain; charset=UTF-8 But *which post* are you looking at? blush the wrong one.../ i.e, the one JUST BEFORE your change of subject --- if i look at the ellipsis post, i see the same encoding that you have mentioned sorry for the confusion -- https://mail.python.org/mailman/listinfo/python-list
django - adding a button with parallel functionality
Hi all! I'll try to be clear and brief. I have created a django project some months ago. It is an online survey. Now I want to add a button that when pressed adds something to a database, but does not change any existing functionalities. Brief explanation: button will always be present at the pages with survey questions, when pressed it will simply add a page number (at which page user decided to press the button) to a database, but the user will continue with the survey as normal. (when the button is pressed, the view, template, questions at hand should not change. Nothing changes for the survey subject!) My question is how to simply add this button without interfering with the survey. I do not need detailed instructions with models, views, templates, etc. just brief idea if it is possible to do that without adding new view, reloading view, adding forms etc... (If anyone is interested.. the button will be used to mark when (at which page) the user gets bored with questions, it is for the pilot testing of the survey. pilot users will press the button but then continue with the survey.) Thanks in advance! Best, chip -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 12/8/2013 2:06 PM, rafaella...@gmail.com wrote: Even when you do get what lambda means and how use it, name = lambda args: expression which is a carryover from other languages, is inferior to def name(args): return expression because the function object resulting from lambda does not have a proper name attribute. def people(age): people=[name for name in dic if dic[name]==age] An alternative is [name for name, value in dic.itervalues() if value == age] In Python 3, remove 'iter'. It this is not homework and you are not otherwise forced to start with Python 3, I (and some others here) recommend starting with Python 3. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: django - adding a button with parallel functionality
In article d099a464-6fa6-47a2-8eda-aa87223a0...@googlegroups.com, chip9m...@gmail.com wrote: Hi all! I'll try to be clear and brief. I have created a django project some months ago. It is an online survey. Now I want to add a button that when pressed adds something to a database, but does not change any existing functionalities. Brief explanation: button will always be present at the pages with survey questions, when pressed it will simply add a page number (at which page user decided to press the button) to a database, but the user will continue with the survey as normal. (when the button is pressed, the view, template, questions at hand should not change. Nothing changes for the survey subject!) My question is how to simply add this button without interfering with the survey. I do not need detailed instructions with models, views, templates, etc. just brief idea if it is possible to do that without adding new view, reloading view, adding forms etc... Offhand, it sounds like you need a button wired up to some javascript which fires off an asynchronous HTTP request. But, since you haven't really described anything about the structure of your application, that's just a wild guess. Almost certainly, the real answer has nothing to do with Python, however. -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Eliminate extra variable
-- Forwarded message -- From: Igor Korot ikoro...@gmail.com Date: Sun, Dec 8, 2013 at 12:57 PM Subject: Re: Eliminate extra variable To: Roy Smith r...@panix.com Hi, guys, Thank you for all those valuable suggestions. 2Tim Chase: I guess you missed this: My originalData comes from the database query and so the checking of the data quality is a DB burden. ;-) As to the function: the function purpose is to process the data and give out the list of dates and the dictionary of date:frequency. It's input is the query result, so there is no looping when the function is called. It is called only once. Also, the data comes from either SQLite or mySQL and so to eliminate the difference between those engines dates are processed as strings and converted to dates for the calculation purposes only. Maybe I will need to refactor SQLite processing to get the dates as dates and not a string, but that's probably for the future. so that dates will be kept as the datetime type until the end of the function. As I wrote the dates will be used as the text for the plotting window axis labels and as the labels they should come out as strings, hence the conversion. Thank you. On Sun, Dec 8, 2013 at 12:07 PM, Roy Smith r...@panix.com wrote: In article mailman.3738.1386529877.18130.python-l...@python.org, Mark Lawrence breamore...@yahoo.co.uk wrote: On 08/12/2013 18:58, Tim Chase wrote: On 2013-12-07 23:14, Igor Korot wrote: [big snip] Whenever I need date manipulations I always reach out to this http://labix.org/python-dateutil The problem with dateutil is it's dog slow. Sure, I use it too, when convenience is more important than performance, but have you ever looked at the code for dateutil.parser.parse()? It's worth reading, just for fun. -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
On 2013-12-08 12:58, Igor Korot wrote: Also, the data comes from either SQLite or mySQL and so to eliminate the difference between those engines dates are processed as strings and converted to dates for the calculation purposes only. Maybe I will need to refactor SQLite processing to get the dates as dates and not a string, but that's probably for the future. so that dates will be kept as the datetime type until the end of the function. As I wrote the dates will be used as the text for the plotting window axis labels and as the labels they should come out as strings, hence the conversion. Sqlite can do this automatically if you tell it to upon connecting: import sqlite3 conn = sqlite3.connect('x.sqlite', ...detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) cur.execute(create table foo (s date);) sqlite3.Cursor object at 0x7f7f31665570 import datetime today = datetime.date.today() cur.execute(insert into foo(s) values (?), (today,)) sqlite3.Cursor object at 0x7f7f31665570 cur.execute(select * from foo) sqlite3.Cursor object at 0x7f7f31665570 r = cur.fetchone() print r (datetime.date(2013, 12, 8),) Note that it returns a datetime.date, the same as it was defined. -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: Eliminate extra variable
On Sun, 8 Dec 2013 12:58:18 -0800, Igor Korot ikoro...@gmail.com wrote: It's input is the query result, so there is no looping when the function is called. It is called only once. Then why save part of the result in an instance attribute? Just return all of the results as a tuple. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, Dec 8, 2013 at 2:33 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Sat, 07 Dec 2013 20:21:06 -0800, Mark Janssen wrote: Is it just me, or is this basically useless? class object | The most *base* type [[Terry Reedy:]] How about something like. The default top *superclass* for all Python classes. How 'bout you fools just admit that you didn't realize you've been confused this whole time? (It *is* possible isn't it?) Mr. Ewing says base has to be interpreted as an *adjective* because otherwise it would mean the BOTTOM (like the BASE of the pyramid), while Terry responds that it is the TOP (*super*class). Earlier, Steven D'Aprano wanted to argue that this distinction was irrelevant, What are you talking about? Until this very post, I haven't made any comments in this thread. It was a few months ago. You do know what I'm talking about because you just expounded with the exact same argument below. It's like a broken record. (Now if *I* sound like a broken record, it's because no seems to see the obvious, but carry on.) but obviously it can't very well be both at once now cannit? Family trees and other hierarchies, including class inheritance diagrams, have a *relative* direction not an absolute direction. We can all agree that Fred and Wilma are the parents of Pebbles, but it doesn't really matter whether we draw the family tree like this: Fred Wilma (diagrams best viewed in a fixed-width font | | like Courier, Monaco or Lucinda Typewriter) +++ | Pebbles (inheritance goes *down* the page from ancestors to descendants) or like this: Pebbles | +++ | | Fred Wilma (inheritance goes *up* the page from ancestors to descendants). What matters is the relationships between the entities, not the specific direction they are drawn in relative to some imaginary absolute space. [yadda, yagni, yadda] But, there IS A DIFFERENCE. Let me explain the concept of a object model (or type model if you prefer). In a family inheritance tree, there is this difference -- called the calendar -- which imposes an ordering which can't be countermanded by flipping your silly chart around. You made a bullshit example to simply argue a point and *fooled yourself* into ignoring this. Yes? Likewise, WITH A COMPUTER, there is a definite order which can't be countermanded by simply having this artifice called Object. If you FEE(L)s hadn't noticed (no longer using the insult foos out of respect for the sensativities of the brogrammers), this artifice has just been *called on the floor* with this little innocent question that fired up this discussion again (don't hate the messenger). Again: people entering the community are pointing out a problem -- that Object is both trying to be the BASE and the SUPERclass of all objects. CS554: A type/object *model* has to define the relationship of these nice abstractions so that they can be mapped to the *actual concreteness* of the machine. And there, bro, there is an ordering. You're not going to magically flip the hierarchy so that your bitless Object becomes a machine word that is the base of all your types. You've been fooled by the magic of the Turing Machine. The modern computer mollifies you with the illusion of total abstraction where there are no bits or 1s and 0s involved, but yea, it did not turn out that way. (Note bene: as a comparison, C++ is very UNAMBIGUOUS about this fact -- all objects inherit from concrete machine types, which is why it remains important, *despite* being one of the worst to do OOP in. Its *type model* is probably the most clear of any object-oriented language). Likewise it doesn't matter whether we draw class hierarchies from the top down or the bottom up or even sidewise: Have you caught it by now, friends: IT MATTERS TO THE COMPUTER. With some apologies for Ned for attempting to be neutral. Apparently you guys are philosophers more than Computer Engineers. MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
Mark Janssen wrote: Mr. Ewing says base has to be interpreted as an *adjective* because otherwise it would mean the BOTTOM (like the BASE of the pyramid), Not exactly -- a native English speaker would say something like the bottommost class if that's what they meant. Or they would say the most basic class to mean the simplest one -- but that's not quite what we mean either. The only way that most base class makes grammatical sense is if you interpret base as meaning undesirable, as in base metal (i.e. a non-precious metal), base instinct (the kind of animal urges that humans are meant to be too good for), etc. while Terry responds that it is the TOP (*super*class). Yeah, top or bottom only conveys the right idea if you assume the diagram is drawn a particular way up. Which is why I like the term base class -- you just need to be careful with the grammar! -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On 07/12/2013 01:35, Terry Reedy wrote: On 12/6/2013 12:03 PM, Mark Lawrence wrote: Is it just me, or is this basically useless? help(object) Help on class object in module builtins: class object | The most base type Given that this can be interpreted as 'least desirable', it could definitely be improved. Surely a few more words, How about something like. '''The default top superclass for all Python classes. Its methods are inherited by all classes unless overriden. ''' When you have 1 or more concrete suggestions for the docstring, open a tracker issue. Terry's suggestion above remains odds on favourite on the grounds that there have been no other suggestions. I'll give it another day, then raise a tracker issue, unless the overwhelming smell of pot that has been drifting around this thread knocks me unconscious. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
rafaella...@gmail.com wrote: def people(age): people=lambda age: [name for name in dic if dic[name]==age] but i don't get the lambda age part. Just to explain: YBM has tried to sabotage you by posting a solution that uses a couple of advanced Python features (lambda and list comprehensions) that a beginner would be unlikely to know about. The idea is that if you had simply handed that code in as-is, your teacher would know that you had almost certainly not written it yourself. Anyhow, you seem to be almost there. The only thing now is that your function needs to *return* the result instead of printing it out. To illustrate with a different example, you currently have a function like this: def add(a, b): print a + b This is fine as far as it goes, but the drawback is that printing out the result is all it will ever do. You're being asked to write a function like this: def add(a, b): return a + b This is much more useful, because you can do anything you like with the result, e.g. print add(2, 3) * add(4, 5) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 12/08/2013 12:17 PM, Chris Angelico wrote: On Mon, Dec 9, 2013 at 6:06 AM, rafaella...@gmail.com wrote:[...] Also, your posts are acquiring the slimy stain of Google Groups, which makes them rather distasteful. All your replies are getting double-spaced, among other problems. Please consider switching to an alternative newsgroup reader, or subscribing to the mailing list: https://mail.python.org/mailman/listinfo/python-list To the OP: First, my apologies if my reply ends up trashing your discussion here, but you should know what is behind Mr. Angelico's response. For some time now the Google Group Wars are being fought in this group. There is a (probably very small) clique of Google haters who try present themselves as the community and who try to intimidate anyone posting from Google Groups into using some other means of posting, completely disregarding the fact that for many new people or occasional posters, Google Groups is an order of magnitude easier to use. These people are extremely noisy and obnoxious but *do not* represent the community except in their own minds. I suspect many of them are motivated by political dislike of Google as a corporation, or want to stay with the 1990's technology they invested time in learning and don't want see change. I and many other people post here from Google Groups and you should feel free to too if it is more convenient for you. (Of course you can also use the maillist or usenet if you find them a good solution for *you* but please don't feel compelled to by some loud obnoxious bullies.) As another poster pointed out, if you are able to follow some of the advice at, https://wiki.python.org/moin/GoogleGroupsPython it will help quiet down the anti-Google crowd a little but even if you don't, those without a Google chip on their shoulder will simply skip your posts if they find the Google formatting too annoying. Most of us though will deal with it as adults and try our best to answer your questions. I just thought you should have both sides of the story so to won't take the anti-Google crowd here as gospel. Addressing you last question, I presume you understood the other responses about replacing the print (people) statement in your people() function with return people. The only additional thing I wanted to add is that, people=[name for name in dic if dic[name]==age] is (I would guess) a rather advanced way of doing what you are doing, given where you seem to be in learning about python (but maybe not, in which case ignore the following). The [] thing is called as list comprehension and in described here http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions However, it is just a more concise way of writing: people = [] for n, a in dic.items(): if a == age: people.append (n) return people To understand the above (if you don't already) you'll want to read about the the items() method of dicts: http://docs.python.org/3/tutorial/datastructures.html#looping-techniques http://docs.python.org/3/library/stdtypes.html#mapping-types-dict the append() method of lists, http://docs.python.org/3/tutorial/controlflow.html#for-statements http://docs.python.org/3/library/stdtypes.html#mutable-sequence-types and of course for loops; http://docs.python.org/3/tutorial/controlflow.html#for-statements Hope this helps. -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 09/12/2013 00:08, ru...@yahoo.com wrote: On 12/08/2013 12:17 PM, Chris Angelico wrote: On Mon, Dec 9, 2013 at 6:06 AM, rafaella...@gmail.com wrote:[...] Also, your posts are acquiring the slimy stain of Google Groups, which makes them rather distasteful. All your replies are getting double-spaced, among other problems. Please consider switching to an alternative newsgroup reader, or subscribing to the mailing list: https://mail.python.org/mailman/listinfo/python-list To the OP: First, my apologies if my reply ends up trashing your discussion here, but you should know what is behind Mr. Angelico's response. For some time now the Google Group Wars are being fought in this group. There is a (probably very small) clique of Google haters who try present themselves as the community and who try to intimidate anyone posting from Google Groups into using some other means of posting, completely disregarding the fact that for many new people or occasional posters, Google Groups is an order of magnitude easier to use. These people are extremely noisy and obnoxious but *do not* represent the community except in their own minds. I suspect many of them are motivated by political dislike of Google as a corporation, or want to stay with the 1990's technology they invested time in learning and don't want see change. I and many other people post here from Google Groups and you should feel free to too if it is more convenient for you. (Of course you can also use the maillist or usenet if you find them a good solution for *you* but please don't feel compelled to by some loud obnoxious bullies.) As another poster pointed out, if you are able to follow some of the advice at, https://wiki.python.org/moin/GoogleGroupsPython it will help quiet down the anti-Google crowd a little but even if you don't, those without a Google chip on their shoulder will simply skip your posts if they find the Google formatting too annoying. Most of us though will deal with it as adults and try our best to answer your questions. I just thought you should have both sides of the story so to won't take the anti-Google crowd here as gospel. To the OP, please ignore the above, it's sheer, unadulterated rubbish. Nobody has ever been bullied into doing anything. People have however been asked repeatedly to either A) use the link referenced above to avoid sending double spaced crap here from the inferior google groups product or B) use an alternative technology that doesn't send double spaced crap. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, 08 Dec 2013 23:48:57 +, Mark Lawrence wrote: help(object) Help on class object in module builtins: class object | The most base type '''The default top superclass for all Python classes. Its methods are inherited by all classes unless overriden. ''' Terry's suggestion above remains odds on favourite on the grounds that there have been no other suggestions. I'll give it another day, then raise a tracker issue, unless the overwhelming smell of pot that has been drifting around this thread knocks me unconscious. The root class for all Python classes. Its methods are inherited by all classes unless overriden. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
help(object) Help on class object in module builtins: class object | The most base type '''The default top superclass for all Python classes. Its methods are inherited by all classes unless overriden. ''' The root class for all Python classes. Its methods are inherited by all classes unless overriden. *sits back*. -- MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On 09/12/2013 01:09, Mark Janssen wrote: help(object) Help on class object in module builtins: class object | The most base type '''The default top superclass for all Python classes. Its methods are inherited by all classes unless overriden. ''' The root class for all Python classes. Its methods are inherited by all classes unless overriden. *sits back*. Why? If a newbie is encouraged, as everybody is, to use help at the interactive prompt, then surely them seeing The most base type when typing help(object) is of no use to them at all. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On 09/12/2013 00:45, Denis McMahon wrote: On Sun, 08 Dec 2013 23:48:57 +, Mark Lawrence wrote: help(object) Help on class object in module builtins: class object | The most base type '''The default top superclass for all Python classes. Its methods are inherited by all classes unless overriden. ''' Terry's suggestion above remains odds on favourite on the grounds that there have been no other suggestions. I'll give it another day, then raise a tracker issue, unless the overwhelming smell of pot that has been drifting around this thread knocks me unconscious. The root class for all Python classes. Its methods are inherited by all classes unless overriden. Thanks Denis, you've reminded me why I asked in the first place. What methods, if any does it provide? Are they all abstract? etc??? Personally I'm not really interested, but a newbie might well be and hence might wonder what the hell is going on. If and only if the situation can be improved I'll raise an issue, if not I'll quietly let it drop, and consider more important things, like why are Australia currently thrashing England at cricket? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
Le 09.12.2013 01:00, Gregory Ewing a écrit : rafaella...@gmail.com wrote: def people(age): people=lambda age: [name for name in dic if dic[name]==age] but i don't get the lambda age part. Just to explain: YBM has tried to sabotage you by posting a solution that uses a couple of advanced Python features (lambda and list comprehensions) that a beginner would be unlikely to know about. Oh! I've been caught! ;-) My point is not that I had a problem with the OP (btw asking for homework in a public group always irrates me), but that the teacher of the OP is incredibly stupid and illiterate (or should I say illluterate ?) So I tried to catch both. -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, 08 Dec 2013 23:48:57 +, Mark Lawrence wrote: Terry's suggestion above remains odds on favourite on the grounds that there have been no other suggestions. I'll give it another day, then raise a tracker issue, It's not merely the default superclass, it *is* the superclass to everything. In Python 3, you cannot create an object that doesn't derive from object. (At least not in pure Python -- perhaps you could do so in a C extension class?) Top is misleading, because it assumes that class diagrams are always drawn with ancestors at the top and descendants at the bottom. No need to say that methods are inherited unless overridden, it goes without saying that you can override methods. object: The most fundamental base class for all Python classes and the root of the class inheritance hierarchy. All classes inherit from object. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
Le 08.12.2013 20:06, rafaella...@gmail.com a écrit : i get it, thanks a lot i wrote a different one and it works def people(age): people=[name for name in dic if dic[name]==age] print(people) No it doesn't. You are printing things not returning something. and combine_list is the most stupidest function you could write in Python, as it is built-in with the name 'zip'. name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] dic = dict(zip(name,age)) def people(age): ... ''' How stupid it is to write three line for a one-line function''' ... return [name for name in dic if dic[name]==age] ... people(20) ['Gary', 'Alice', 'Frank'] Sorry for having being rude, but : 1. you shouldn't post raw homework in any kind of public group (aren't you supposed to learn something by yourself ?) 2. your teacher is a nut. -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
Le 08.12.2013 19:32, rafaella...@gmail.com a écrit : On Sunday, December 8, 2013 6:27:34 PM UTC, bob gailer wrote: On 12/8/2013 12:59 PM, rafaella...@gmail.com wrote: i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age. please help Welcome to the python list. Thanks for posting a question. If you were hoping for one of us to write the program for you ... well that's not what we do on this list. Please post the code you have so far and tell us exactly where you need help. Also tell us what version of Python, what OS, and what you use to write and run Python programs. name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] dic={} def combine_lists(name,age): for i in range(len(name)): dic[name[i]]= age[i] combine_lists(name,age) print dic def people(age): people=lambda age: [name for name in dic if dic[name]==age] people(20) this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result You didn't write a function which return a result, so you have no result. -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Mon, 09 Dec 2013 01:43:43 +, Mark Lawrence wrote about object: What methods, if any does it provide? Are they all abstract? etc??? Pretty much nothing useful :-) py dir(object) ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] What few methods there are typically do nothing, or nothing interesting. A few implement basic functionality, e.g. __eq__ performs equality based on identity (an object is equal to itself and nothing else). -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
What methods, if any does it provide? Are they all abstract? etc??? Pretty much nothing useful :-) py dir(object) [...] So (prodding the student), Why does everything inherit from Object if it provides no functionality? Practicality-beats-purity-yours? -- MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Mon, Dec 9, 2013 at 10:01 AM, Mark Janssen dreamingforw...@gmail.com wrote: (Note bene: as a comparison, C++ is very UNAMBIGUOUS about this fact -- all objects inherit from concrete machine types, which is why it remains important, *despite* being one of the worst to do OOP in. Its *type model* is probably the most clear of any object-oriented language). Factually wrong. In C++, it is actually *impossible* to inherit from a concrete machine type, by which presumably you mean the classic types int/char/float etc. struct foo: public int { foo() {} }; 1.cpp:1:20: error: expected class-name before ‘int’ 1.cpp:1:20: error: expected ‘{’ before ‘int’ 1.cpp:2:1: error: expected unqualified-id before ‘{’ token Okay, that's a parse error. Maybe if we avoid the language keyword? typedef int integer; struct foo: public integer { foo() {} }; 1.cpp:4:1: error: expected class-name before ‘{’ token Nope. There are two completely different groups here: the basic types (called here [1] Fundamental data types) and the structure types. The latter are created by the struct/class keyword and can use inheritance. The former... aren't. Not every C++ type is part of the type hierarchy. This is actually somewhat true of Python, too, but the set of types that are unavailable for inheritance is much smaller and less useful. You can't inherit from the 'function' type, for instance: class foo(type(lambda:1)): pass Traceback (most recent call last): File pyshell#80, line 1, in module class foo(type(lambda:1)): TypeError: type 'function' is not an acceptable base type And yet class 'function' inherits from class 'object', so it's not entirely outside in the way C++ int is. And I can apparently subclass module, though not generator, and unsurprisingly NoneType can't be inherited from. (Though you can instantiate it, and it's probably the only class that will appear to have no return value from instantiation.) C++ has you *compose* structs/classes from primitives, but this is not the same as inheritance. They're completely separate concepts. ChrisA [1] http://www.cplusplus.com/doc/tutorial/variables/ -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Mon, Dec 9, 2013 at 1:41 PM, Mark Janssen dreamingforw...@gmail.com wrote: What methods, if any does it provide? Are they all abstract? etc??? Pretty much nothing useful :-) py dir(object) [...] So (prodding the student), Why does everything inherit from Object if it provides no functionality? Practicality-beats-purity-yours? Nothing useful to call directly. An int has some useful methods in Python: (258).to_bytes(2,little) b'\x02\x01' So does a list: [1,4,1,5,9].count(1) 2 But there's nothing you'd normally want to call from object itself (except maybe __repr__). There *are*, however, important pieces of default functionality. Steven mentioned __eq__, and there's also its pair __hash__. The default system works because the root type provides implementations of those two functions: a = object() b = object() a == b False d = {a:A, b:B} d[a] 'A' And it's important that these sorts of things work, because otherwise a simple Python class would look like this: class Foo: def __new__(self): pass def __init__(self): pass def __hash__(self): return id(self) def __eq__(self, other): return self is other # ... This repetition is exactly what inheritance is good at solving. Therefore putting that functionality into a base class makes sense; and since everything MUST have these functions to be able to be used plausibly, putting them in the lowest base class of all makes the most sense. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Monday, December 9, 2013 8:11:47 AM UTC+5:30, zipher wrote: What methods, if any does it provide? Are they all abstract? etc??? Pretty much nothing useful :-) py dir(object) [...] So (prodding the student), Why does everything inherit from Object if it provides no functionality? Thats right. What does a collection object like [] or the empty set ∅ (assuming the unicode-gods will allow and bless that) do when it collects nothing? Lets make sure all lists and sets start non-empty. And why have a stupid number like 0 when it counts nothing? Lets go back to roman numerals which is so much more… Practicality-beats-purity-yours? Practical!!⸮¿¡ PS Can some kind soul inform me whether I could convince GG to unicode my post? -- https://mail.python.org/mailman/listinfo/python-list
Re: ASCII and Unicode
On Monday, December 9, 2013 1:41:41 AM UTC+5:30, giacomo boffi wrote: blush the wrong one.../ i.e, the one JUST BEFORE your change of subject --- if i look at the ellipsis post, i see the same encoding that you have mentioned sorry for the confusion And thank you for pointing the way to the culprit, viz. GG trying to be too clever. [Since you neglected to close your blush I am included in it :-) ] -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Mon, Dec 9, 2013 at 11:08 AM, ru...@yahoo.com wrote: I suspect many of them are motivated by political dislike of Google as a corporation, or want to stay with the 1990's technology they invested time in learning and don't want see change. Neither. I don't at all hate Google (I quite like the company, and what it's done for the world), and I use plenty of other Google services - as you can see, I'm posting from gmail here. The only thing I call out against is Google Groups, because it is buggy. I'll cry out against anything else that's buggy, too. Of course, I'll first try to do things quietly (bug reports to the maintainers), but ultimately, the solution to buggy software is to NOT USE IT. If Google doesn't care enough about Groups to bring it up to the standard, then their penalty has to be reduced usage. In fact, Rurpy, you are actually encouraging the faulty system, because you're providing ad impressions and usage stats every time you read or write via GG. When less-buggy systems see more use than more-buggy systems, big companies have an incentive to fix bugs. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, Dec 8, 2013 at 6:44 PM, Chris Angelico ros...@gmail.com wrote: On Mon, Dec 9, 2013 at 10:01 AM, Mark Janssen dreamingforw...@gmail.com wrote: (Note bene: as a comparison, C++ is very UNAMBIGUOUS about this fact -- all objects inherit from concrete machine types, which is why it remains important, *despite* being one of the worst to do OOP in. Its *type model* is probably the most clear of any object-oriented language). Factually wrong. In C++, it is actually *impossible* to inherit from a concrete machine type, by which presumably you mean the classic types int/char/float etc. Wow, you guys trip me out, but I guess I've been working in a different universe where I was mapping classes into basic types (using generic programming along with typedef). I'm going to have to re-think all this confusion. But, in any case, if you don't have a way to map your abstract objects into machine types, you're working on magic, not computer science. MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Mon, Dec 9, 2013 at 2:05 PM, Mark Janssen dreamingforw...@gmail.com wrote: But, in any case, if you don't have a way to map your abstract objects into machine types, you're working on magic, not computer science. Maybe, but that mapping isn't always an inheritance relationship. Ultimately the computer can't work with my data without it being represented in memory and in registers (at least in part - relational database could be considered a type, the full implementation of which is never actually loaded into memory), but the most common way to do this is effectively some form of composition. For instance, C++ has a type called pair (actually a template); what's the most obvious way to define the type pair of integers? Place the first integer, then place the second integer. The pair has two members, first and second. The pair isn't the first integer, nor is it the second integer. It doesn't make sense to inherit pair from integer, so you don't. You compose it of two integers. class Pair(object): # in C++, we'd need to declare these: # int first; # int second; def __init__(self, first, second): self.first, self.second = first, second Calling integer methods on a Pair makes no sense. Which of its members did you want to call that on? Both of them? (Wouldn't make sense if you had a mixed pair, like pairemployee,gun which could be a little awkward to try to fire().) You can't sensibly use a Pair in a context where an integer would be wanted, so it fails LSP. It composes, but does not inherit from, int. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, 08 Dec 2013 18:58:09 -0800, rusi wrote: PS Can some kind soul inform me whether I could convince GG to unicode my post? Does GG not give you some way of inspecting the post's full headers? Anyway, here you go: Content-Type: text/plain; charset=UTF-8 Your plan succeeded. Personally, I wouldn't stress too much about this. While it would be nice, and desirable, for GG to always use UTF-8 instead of picking a different encoding based on the phase of the moon, the main thing is that it picks a valid encoding. So far I see no reason to accuse GG of using an invalid encoding. Valid but legacy encodings are better than mojibake :-) -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
Thanks for the info. On Monday, December 9, 2013 9:46:30 AM UTC+5:30, Steven D'Aprano wrote: On Sun, 08 Dec 2013 18:58:09 -0800, rusi wrote: PS Can some kind soul inform me whether I could convince GG to unicode my post? Does GG not give you some way of inspecting the post's full headers? Well I spent half hour looking around -- both inside GG and of course searching before asking. Anyway, here you go: Content-Type: text/plain; charset=UTF-8 Your plan succeeded. Personally, I wouldn't stress too much about this. While it would be nice, and desirable, for GG to always use UTF-8 instead of picking a different encoding based on the phase of the moon, the main thing is that it picks a valid encoding. So far I see no reason to accuse GG of using an invalid encoding. Valid but legacy encodings are better than mojibake :-) Heh! I'm hardly a heavy-duty user of unicode -- just keeping track of bugs and workarounds. I am of course using 'bug' in a wide pragmatic sense of preventing communication. Mojibake is a technical problem. Non (human) communication is a more fundamental problem. Keeping an eye on the latter is (for me) a bigger issue than the former. -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On 12/8/2013 8:43 PM, Mark Lawrence wrote: On 09/12/2013 00:45, Denis McMahon wrote: On Sun, 08 Dec 2013 23:48:57 +, Mark Lawrence wrote: help(object) Help on class object in module builtins: class object | The most base type '''The default top superclass for all Python classes. Its methods are inherited by all classes unless overriden. ''' I said 'top' instead of 'bottom' or 'base' to loosen up thinking a bit. I did not expect Mark to make a mound out of that flip. Terry's suggestion above remains odds on favourite on the grounds that there have been no other suggestions. I'll give it another day, then raise a tracker issue, unless the overwhelming smell of pot that has been drifting around this thread knocks me unconscious. The root class for all Python classes. Its methods are inherited by all classes unless overriden. 'Root' is even better, since it does not depend on whether a tree is drawn up or down. Thanks. Thanks Denis, you've reminded me why I asked in the first place. What methods, if any does it provide? Good question. dir(object) ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] Are they all abstract? etc??? No. Personally I'm not really interested, but a newbie might well be and hence might wonder what the hell is going on. For everything else, help lists the special name methods directly associated with the object, along with docstrings. help(C) Help on class C in module __main__: class C(builtins.object) | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) I think help should do the same for object object.__hash__.__doc__ 'x.__hash__() == hash(x)' is equivalent to | __abs__(...) | x.__abs__() == abs(x) etc printed for help(int) The fact that __dict__ does not exist for object but is only added for subclasses explains why one must subclass object to get instances that allow attributes. o = object() o.a = 1 Traceback (most recent call last): File pyshell#8, line 1, in module o.a = 1 AttributeError: 'object' object has no attribute 'a' c = C() c.a=1 If and only if the situation can be improved I'll raise an issue I think it can be. If you prefer me to open the issue, say so. We should look for existing issues, and closed issues that rejected change. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On 12/08/2013 05:27 PM, Mark Lawrence wrote: On 09/12/2013 00:08, ru...@yahoo.com wrote: On 12/08/2013 12:17 PM, Chris Angelico wrote: On Mon, Dec 9, 2013 at 6:06 AM, rafaella...@gmail.com wrote:[...] [...] To the OP, please ignore the above, it's sheer, unadulterated rubbish. Nobody has ever been bullied into doing anything. People have however been asked repeatedly to either A) use the link referenced above to avoid sending double spaced crap here from the inferior google groups product or B) use an alternative technology that doesn't send double spaced crap. Mark, I appreciate your calm and reasonable requests for people to checkout the page you gave a link to, that's why I repeated your advice. It is also why I responded to Chris and not to you. However it does not change the fact that people here have responded in rather extreme way to GG posts including calling GG users twits and claiming GG posts damage their eyesight, as well as repeatedly denying the obvious fact that GG is much easier to use for many than to subscribe to a usenet provider or to a mailing list. One frequently sees words like crap, slimy, rubbish etc to describe GG posts which is pretty intimating to people who just want some help with a python question using a tool they already know how to use and have had no complaints about in other places. -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, 08 Dec 2013 15:01:59 -0800, Mark Janssen wrote: On Sun, Dec 8, 2013 at 2:33 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Sat, 07 Dec 2013 20:21:06 -0800, Mark Janssen wrote: Is it just me, or is this basically useless? class object | The most *base* type [[Terry Reedy:]] How about something like. The default top *superclass* for all Python classes. How 'bout you fools just admit that you didn't realize you've been confused this whole time? (It *is* possible isn't it?) Mr. Ewing says base has to be interpreted as an *adjective* because otherwise it would mean the BOTTOM (like the BASE of the pyramid), while Terry responds that it is the TOP (*super*class). Earlier, Steven D'Aprano wanted to argue that this distinction was irrelevant, What are you talking about? Until this very post, I haven't made any comments in this thread. It was a few months ago. You do know what I'm talking about because you just expounded with the exact same argument below. It's like a broken record. While I am gratified that you apparently memorise and obsess over things I wrote months ago, I'm sorry to tell you that I wasn't lying when I said that I didn't know what you were talking about. I had no idea that you were referring to a completely different conversation, nor do I recall every post I write here. If I repeated the same argument, it is because the argument is still valid. Drawing the root of the tree at the top of the page is just a convention, just driving on the left side of the road, or calling the elected head of state Prime Minister. There are other ways to do such things which are equally valid, and so long as both parties agree on the convention, it doesn't matter whether you write from left-to-right like in Australia, right-to-left like in Egypt, or alternate like in Israel. (Now if *I* sound like a broken record, it's because no seems to see the obvious, but carry on.) It must be such a trial to be the only sane man in a world gone mad. [...] What matters is the relationships between the entities, not the specific direction they are drawn in relative to some imaginary absolute space. [yadda, yagni, yadda] But, there IS A DIFFERENCE. Let me explain the concept of a object model (or type model if you prefer). In a family inheritance tree, there is this difference -- called the calendar -- which imposes an ordering which can't be countermanded by flipping your silly chart around. You made a bullshit example to simply argue a point and *fooled yourself* into ignoring this. Yes? No. You haven't explained anything, you have merely made an assertion with no supporting evidence at all. In a family tree of ancestors and descendants, the relationship being draw is time-based. Ancestors exist before descendants. Descendants are derived in some way from ancestors, not the other way around. We all agree that your father existed before you. The temporal direction of the relationship is absolutely fixed, past before present, ancestors before descendants. We can agree on this. Explain to me this: what (apart from mere human convention) imposes the ordering past must be at the top of the page? If you are reading this as email, your mail client very likely has an option to sort message in order that they were received, either most- recent at the top or oldest at the top. Do you really mean to imply that one of those is logical and the other is delusional? Likewise, WITH A COMPUTER, there is a definite order which can't be countermanded by simply having this artifice called Object. If you FEE(L)s hadn't noticed (no longer using the insult foos out of respect for the sensativities of the brogrammers), this artifice has just been *called on the floor* with this little innocent question that fired up this discussion again (don't hate the messenger). Again: people entering the community are pointing out a problem -- that Object is both trying to be the BASE and the SUPERclass of all objects. How is this a problem? They mean the same thing. A television is both an appliance and a device. object is both the base class and a superclass of all other classes. CS554: A type/object *model* has to define the relationship of these nice abstractions so that they can be mapped to the *actual concreteness* of the machine. And there, bro, there is an ordering. Yes, the ordering is that the subclass is derived from the superclass. Nobody disputes that. But we can show that relationship using any convention we like: superclass - subclass subclass - superclass superclass extended by subclass subclass extends superclass superclass ↓ subclass subclass ↑ superclass Python syntax: class MySubclass(MySuperclass): ... Smalltalk syntax: MySuperclass :subclass #MySubclass Java syntax: class MySubclass extends MySuperclass {...} You're not going to magically flip the hierarchy so that
Re: python programming help
On 12/08/2013 08:05 PM, Chris Angelico wrote: On Mon, Dec 9, 2013 at 11:08 AM, ru...@yahoo.com wrote: I suspect many of them are motivated by political dislike of Google as a corporation, or want to stay with the 1990's technology they invested time in learning and don't want see change. Neither. I don't at all hate Google (I quite like the company, and what it's done for the world), and I use plenty of other Google services - as you can see, I'm posting from gmail here. If the shoe doesn't fit, don't wear it. There have certainly been others who have publicly railed against Google. The only thing I call out against is Google Groups, because it is buggy. And yet you are publicly on record as referring to GG users as twits. I'll cry out against anything else that's buggy, too. Of course, I'll first try to do things quietly (bug reports to the maintainers), but ultimately, the solution to buggy software is to NOT USE IT. If Google doesn't care enough about Groups to bring it up to the standard, then their penalty has to be reduced usage. In fact, Rurpy, you are actually encouraging the faulty system, because you're providing ad impressions and usage stats every time you read or write via GG. When less-buggy systems see more use than more-buggy systems, big companies have an incentive to fix bugs. We all use buggy software every day. *Every* piece of non-trival software is buggy -- you already know that. So you are saying that bugs that annoy *you* are ones that *others* should change their practice to join your boycott to fix. You sound like some Unix hard-asses of the 1990's who, by god, weren't going pollute their software with any kind of MS Windows compatibility. No supporting a broken OS for them. They would keep the software pure and Unix-only and force Microsoft to fix their broken OS. Well, most of that software and those programmers have been eliminated by Darwinian selection, and today cross-platform (or Windows only) software is the norm. So good luck on your crusade to force Google to do things the way you think is right. (Especially given the large and growing number of Python project mailing lists *hosted* on Google Groups.) Until you're successful, I will try to encourage GG users to post more compatibly to avoid pissing off the old farts, do what I can to support Rusi's attempt to put together a tool to make it easier to do so, and finally, live with double-spaced crap because that is the lesser of two evils, the other being creating an excessively picky and hostile place for newcomers who just want to learn more about Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
why can't we all just get along? Rodney King, RIP -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Monday, December 9, 2013 10:37:38 AM UTC+5:30, ru...@yahoo.com wrote: On 12/08/2013 05:27 PM, Mark Lawrence wrote: On 09/12/2013 00:08, wrote: On 12/08/2013 12:17 PM, Chris Angelico wrote: On Mon, Dec 9, 2013 at 6:06 AM, rafaell wrote: [...] To the OP, please ignore the above, it's sheer, unadulterated rubbish. Nobody has ever been bullied into doing anything. People have however been asked repeatedly to either A) use the link referenced above to avoid sending double spaced crap here from the inferior google groups product or B) use an alternative technology that doesn't send double spaced crap. Mark, I appreciate your calm and reasonable requests for people to checkout the page you gave a link to, that's why I repeated your advice. It is also why I responded to Chris and not to you. Yes agreed. However it does not change the fact that people here have responded in rather extreme way to GG posts including calling GG users twits and claiming GG posts damage their eyesight, as well as repeatedly denying the obvious fact that GG is much easier to use for many than to subscribe to a usenet provider or to a mailing list. One frequently sees words like crap, slimy, rubbish etc to describe GG posts which is pretty intimating to people who just want some help with a python question using a tool they already know how to use and have had no complaints about in other places. About the last -- no complaints about (that) in other places -- Ive recently seen that on the html/stylesheets/javascript lists (not sure which) there are also annoyed complaints about GG. About the rest -- when people get annoyed they say and do things they would not otherwise do. The sensible not-yet-annoyed-enough-to-lose-the-head folks should try to cure the annoyance rather than get annoyed with it -- dont you think? In short if we are programmers we should be thinking bug-fixes when we are bugged :-) And what is put up here https://wiki.python.org/moin/GoogleGroupsPython (only yesterday BTW) is a dynamically loadable GG-bugfix. -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On 12/08/2013 09:46 PM, rusi wrote: On Monday, December 9, 2013 9:46:30 AM UTC+5:30, Steven D'Aprano wrote: On Sun, 08 Dec 2013 18:58:09 -0800, rusi wrote: [...] Does GG not give you some way of inspecting the post's full headers? Well I spent half hour looking around -- both inside GG and of course searching before asking. If you click on the little down triangle to the right of the reply button for a message, you'll get a menu that includes Show Original. You can see the headers including the Content-Type: in that original. Of course this means you have to post first and find out after... -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, 08 Dec 2013 18:41:47 -0800, Mark Janssen wrote: What methods, if any does it provide? Are they all abstract? etc??? Pretty much nothing useful :-) py dir(object) [...] So (prodding the student), Why does everything inherit from Object if it provides no functionality? You cut out the part of my post where I explained that object does in fact provide a minimal set of useful functionality. The example I gave was __eq__ (equal), but there is also __ne__ (not equal), __hash__ (hashing), __str__ and __repr__ (although many classes will wish to override them) and a few more. They're useful, even necessary, but hardly exciting. The other reasons for inheriting from object include: - If all classes are part of a single hierarchy, it must logically end at one (or more, if you support multiple inheritance, which Python does) bases classes. (Unless there are loops, which are generally prohibited in all OOP systems I know of). The simplest way to do this is with a single base class. - Pragmatism: it was the easiest way to unify types and classes way back in Python 2.2, prior to which there was no single hierarchy and all classes were (in a sense) distinct. Pedants will of course realise that Python 2 has *two* object hierarchies, classic classes which don't share a base class, and types (a.k.a. new style classes) which do. In Python 3, classic classes are gone, and there is a single class hierarchy with object the base. There may be other reasons. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Monday, December 9, 2013 10:56:28 AM UTC+5:30, ru...@yahoo.com wrote: On 12/08/2013 09:46 PM, rusi wrote: On Monday, December 9, 2013 9:46:30 AM UTC+5:30, Steven D'Aprano wrote: On Sun, 08 Dec 2013 18:58:09 -0800, rusi wrote: [...] Does GG not give you some way of inspecting the post's full headers? Well I spent half hour looking around -- both inside GG and of course searching before asking. If you click on the little down triangle to the right of the reply button for a message, you'll get a menu that includes Show Original. You can see the headers including the Content-Type: in that original. Thanks rurpy -- I only looked for how one may set and not just what is. So now I look at my own post in GG and see Content-Type: text/plain; charset=UTF-8 So far so good. However when I point firefox at my own post in the archive https://mail.python.org/pipermail/python-list/2013-December/662015.html firefox shows encoding as Windows-1252. Note Ive looked at a dozen random pages and for all FF shows encoding as utf-8 except the python list archive ones which show as Win 1252 Note looking into the html I see META http-equiv=Content-Type content=text/html; charset=us-ascii How us-ascii becomes Win-1252 is outside the reach of my meagre intelligence! Though I still suspect something is not quite right with the python mailing-list and/or archive in respect of char encodings. [Am I beginning to sound like jmf is my guru :-) ] -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
Steven D'Aprano st...@pearwood.info writes: - If all classes are part of a single hierarchy, it must logically end at one (or more, if you support multiple inheritance, which Python does) bases classes. (Unless there are loops, which are generally prohibited in all OOP systems I know of). The simplest way to do this is with a single base class. The original Lisp Machine Flavors system (one of the ancestors of the Common Lisp Object System) allowed inheritance to be an arbitrary directed graph -- possibly with cycles. I don't believe that this was done for any deep principled reason, but rather it was just permitted because the algorithm for computing method resolution order didn't actually care whether there were inheritance cycles -- it still terminated and returned an ordered list of component classes. I do not remember seeing any code that made use of this ability, so don't ask me if it was good for anything, but it was definitely there... -- Alan Bawden -- https://mail.python.org/mailman/listinfo/python-list
Re: python programming help
On Mon, Dec 9, 2013 at 4:07 PM, ru...@yahoo.com wrote: However it does not change the fact that people here have responded in rather extreme way to GG posts including calling GG users twits and claiming GG posts damage their eyesight, as well as repeatedly denying the obvious fact that GG is much easier to use for many than to subscribe to a usenet provider or to a mailing list. One frequently sees words like crap, slimy, rubbish etc to describe GG posts which is pretty intimating to people who just want some help with a python question using a tool they already know how to use and have had no complaints about in other places. Please note though that there is a difference between describing the users as twits and describing the posts as slimy. Suppose you write a letter (the sort that goes on a slab of dead tree) and, instead of placing it in an envelope and putting a stamp on it, you hand it to the Arac News Insertion Device[1] to do the enveloping for you. He does a reasonable job of it, but he uses cobwebs instead of paper for the envelope. Sure, it's still readable... but your readers now have to rub off a whole lot of cobwebs before they can read what you said. That makes your post distasteful, without it being at all your fault - other than choosing to use Arac's service. That's how I see Google Groups posts. Someone's gone looking for help about Python and has found that. It's not their fault that they don't know about alternatives; so I point out the alternatives. ChrisA [1] http://math.boisestate.edu/gas/princess_ida/webop/pi_04.html On the whole we are Not intelligent... -- https://mail.python.org/mailman/listinfo/python-list
[issue19921] Path.mkdir(0, True) always fails
Vajrasky Kok added the comment: Fails on Windows Vista. ...s..s..s..s...F. .. == FAIL: test_mkdir_parents (__main__.PathTest) -- Traceback (most recent call last): File Lib\test\test_pathlib.py, line 1502, in test_mkdir_parents self.assertEqual(stat.S_IMODE(p.stat().st_mode), 0o555 mode) AssertionError: 511 != 365 == FAIL: test_mkdir_parents (__main__.WindowsPathTest) -- Traceback (most recent call last): File Lib\test\test_pathlib.py, line 1502, in test_mkdir_parents self.assertEqual(stat.S_IMODE(p.stat().st_mode), 0o555 mode) AssertionError: 511 != 365 -- Ran 326 tests in 3.293s FAILED (failures=2, skipped=90) This line is problematic. self.assertEqual(stat.S_IMODE(p.stat().st_mode), 0o555 mode) From http://docs.python.org/2/library/os.html#os.chmod: Note Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored. In Django, we skip chmod test on Windows. https://github.com/django/django/blob/master/tests/staticfiles_tests/tests.py#L830 But this line is okay: self.assertEqual(stat.S_IMODE(p.parent.stat().st_mode), mode) So we should just skip that particular problematic line on Windows. -- nosy: +vajrasky ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19921 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19928] Implement cell repr test
New submission from Serhiy Storchaka: Repr test for cell is empty. Proposed patch implements it. -- components: Tests files: test_cell_repr.patch keywords: patch messages: 205528 nosy: serhiy.storchaka, zach.ware priority: normal severity: normal stage: patch review status: open title: Implement cell repr test type: enhancement versions: Python 2.7, Python 3.3, Python 3.4 Added file: http://bugs.python.org/file33039/test_cell_repr.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19928 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19876] selectors (and asyncio?): document behaviour on closed files/sockets
Charles-François Natali added the comment: The test is failing on Windows buildbot: http://buildbot.python.org/all/builders/x86%20Windows%20Server%202003%20%5BSB%5D%203.x/builds/1851/steps/test/logs/stdio == ERROR: test_unregister_after_fd_close_and_reuse (test.test_selectors.DefaultSelectorTestCase) -- Traceback (most recent call last): File E:\Data\buildslave\cpython\3.x.snakebite-win2k3r2sp2-x86\build\lib\test\test_selectors.py, line 122, in test_unregister_after_fd_close_and_reuse os.dup2(rd2.fileno(), r) OSError: [Errno 9] Bad file descriptor == ERROR: test_unregister_after_fd_close_and_reuse (test.test_selectors.SelectSelectorTestCase) -- Traceback (most recent call last): File E:\Data\buildslave\cpython\3.x.snakebite-win2k3r2sp2-x86\build\lib\test\test_selectors.py, line 122, in test_unregister_after_fd_close_and_reuse os.dup2(rd2.fileno(), r) OSError: [Errno 9] Bad file descriptor Apparently, dup2() doesn't work on Windows because on Windows, sockets aren't file descriptors, but a different beast... -- status: closed - open ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19876 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19837] Wire protocol encoding for the JSON module
Gregory P. Smith added the comment: upstream simplejson (of which json is an earlier snapshot of) has an encoding parameter on its dump and dumps method. Lets NOT break compatibility with that API. Our users use these modules interchangeably today, upgrading from stdlib json to simplejson when they need more features or speed without having to change their code. simplejson's dumps(encoding=) parameter tells the module what encoding to decode bytes objects found within the data structure as (whereas Python 3.3's builtin json module being older doesn't even support that use case and raises a TypeError when bytes are encountered within the structure being serialized). http://simplejson.readthedocs.org/en/latest/ A json.dump_bytes() function implemented as: def dump_bytes(*args, **kwargs): return dumps(*args, **kwargs).encode('utf-8') makes some sense.. but it is really trivial for anyone to write that .encode(...) themselves. a dump_bytes_to_file method that acts like dump() and calls .encode('utf-8') on all str's before passing them to the write call is also doable... but it seems easier to just let people use an existing io wrapper to do that for them as they already are. As for load/loads, it is easy to allow that to accept bytes as input and assume it comes utf-8 encoded. simplejson already does this. json does not. -- nosy: +gregory.p.smith ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19837 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19925] Add unit test for spwd module
Vajrasky Kok added the comment: Hi Claudiu, thanks for the review and the knowledge that on Windows, we don't have attribute getuid of os. Here is the updated patch. I do not check specifically for Windows but only whether the platform can import spwd module or not. That should be enough. -- Added file: http://bugs.python.org/file33040/unittest_for_spwd_v2.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19925 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19837] Wire protocol encoding for the JSON module
Gregory P. Smith added the comment: So why not put a dump_bytes into upstream simplejson first, then pull in a modern simplejson? There might be some default flag values pertaining to new features that need changing for stdlib backwards compatible behavior but otherwise I expect it's a good idea. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19837 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19572] Report more silently skipped tests as skipped
Serhiy Storchaka added the comment: I have added few comments on Rietveld. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19572 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19929] subprocess: increase read buffer size
New submission from Charles-François Natali: This is a spinoff of issue #19506: currently, subprocess.communicate() uses a 4K buffer when reading data from pipes. This was probably optimal a couple years ago, but nowadays most operating systems have larger pipes (e.g. Linux has 64K), so we might be able to gain some performance by increasing this buffer size. For example, here's a benchmark reading from a subprocess spawning dd if=/dev/zero bs=1M count=100: # before, 4K buffer $ ./python ~/test_sub_read.py 2.72450800300021 # after, 64K buffer $ ./python ~/test_sub_read.py 1.250900044803 The difference is impressive. I'm attaching the benchmark script so that others can experiment a bit (on multi-core machines and also different OSes). -- components: Library (Lib) files: test_sub_read.py messages: 205534 nosy: gregory.p.smith, haypo, neologix, pitrou, sbt, serhiy.storchaka priority: normal severity: normal stage: needs patch status: open title: subprocess: increase read buffer size type: performance versions: Python 3.4 Added file: http://bugs.python.org/file33041/test_sub_read.py ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19929 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19766] test_venv: test_with_pip() failed on AMD64 Fedora without threads 3.x buildbot: urllib3 dependency requires the threading module
Vinay Sajip added the comment: I will look at doing a distlib update shortly - but there's another issue (#19913) that might also require an update - it' not clear yet. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19766 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19690] test_logging test_race failed with PermissionError
Vinay Sajip added the comment: I'll close this for now as the failures seem to have stopped. Though I only added some diagnostics, that might have changed the relative timings enough so the race doesn't surface (for now). -- resolution: - works for me status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19690 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19921] Path.mkdir(0, True) always fails
Serhiy Storchaka added the comment: Thank you Vajrasky. Now this check is skipped on Windows. -- Added file: http://bugs.python.org/file33042/pathlib_mkdir_mode_4.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19921 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com