Cross-Platform ReadKey
I found this site that has the code for readkey for Windows, Unix, and in an updated version, Mac: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 . The Mac object returns a character whether or not a key was pressed. I modified the Windows object to do the same when I downloaded it, but I have no idea how to make the Unix object instantly return either the character or an empty string. Any help??? -- http://mail.python.org/mailman/listinfo/python-list
Modifying Unix ReadKey Code
I found this site that has code for readkey for Windows, Unix, and in an updated version, Mac: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 . The Mac object returns a character whether or not a key was pressed. I modified the Windows object to do the same when I downloaded it, but I have no idea how to make the Unix object to do the same. Any help??? Not to be pushy, but I would like an answer soon. -- http://mail.python.org/mailman/listinfo/python-list
Cross-Platform Readkey (one more try...)
I've posted this before, but not gotten an answer: I found this site that has code that does readkey for Windows, Unix, and in an updated version, Mac: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 The Mac readkey class returns a character whether or not a key was pressed. I modified the Windows class to do the same when I downloaded it, but I have no idea how to make the Unix class to do so. Any help??? -- http://mail.python.org/mailman/listinfo/python-list
Scientific Notation
How can I get a number into scientific notation? I have a preference for the format '1 E 50' (as an example), but if it's well known, it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scientific Notation
No, I mean given a big number, such as 1000, convert it into scientific notation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scientific Notation
Thanks for your help, Alex, Roy and Jorge. I'm new to Python, and programming in general, which might explain my lack of knowledge, Fredrick. -- http://mail.python.org/mailman/listinfo/python-list
Fixed Width Font in Tkinter
How do I make a fixed font width in Tkinter? Here's my code (there's more, of course, but this is the focus of the question): import tkFont Font=tkFont.Font(root=master, family="Courier", size=14) I'm sure it's possible, because it's done in IDLE. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fixed Width Font in Tkinter
Never mind, I got it to work. -- http://mail.python.org/mailman/listinfo/python-list
Clearing the Tkinter Window
I'm a newbie here, especially with Tkinter. I'm writing a program that has 3 phases, if you will, in which I would have to clear the window and insert new widgets. Is this possible, and if so, how? I'm writing my application class based on Frame, if that helps at all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Clearing the Tkinter Window
I don't want to destroy the root, I just want to remove the widgets (the exact opposite of what Martin was saying). I started working on James' idea, but it'll be a while before I have it fully implemented to test. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Scrollbar not working
I'm trying to get a scrollbar bound with a Frame, and I keep on getting a scrollbar, but it doesn't actually scroll. Some help, please? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Scrollbar not working
BTW, experience tells me it is necessary for me to explicitly state that I'm a newbie (otherwise I get rude people saying I should already know such-and-such). -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP: method overriding works in mysterious ways?
Parent.critique() is calling self.critique(), which has been overriden by Child.critique() instead of Parent.critique. It makes perfect sense to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP: method overriding works in mysterious ways?
Oh, I see what you mean. From my experience, the methods are passed down, not referred to from the parent. That is, Parent does have its own critique method, not a reference to Grand_parent.critique(). So when Child calls self.advise, it is calling its inherrited copy. Then, since the inherited Child.advise() from Parent.advise() calls self.critique, it calls it's own overriden critique method. I hope this makes sense. -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP: method overriding works in mysterious ways?
> it calls it's own overriden critique method (overriden meaning the one that did the overriding) -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Scrollbar not working
Martin Franklin wrote: > Dustan wrote: > > I'm trying to get a scrollbar bound with a Frame, and I keep on getting > > a scrollbar, but it doesn't actually scroll. Some help, please? > > > > It can be tricky getting an empty frame to scroll, can you post your > example code so that we might be more helpful. Here is an example of > binding a scroll bar to a Text widget (not exactly the same thing) > It's not an empty frame. It has a label. I was trying to do it with just the label, but it didn't work, and I figured it might be a better idea to try doing it with a frame instead. > > ## import all names from Tkinter > ## bit naughty but I don't mind > from Tkinter import * > > > # root window > root=Tk() > > > # text area > text=Text() > text.pack(side="left", expand="yes", fill="both") > > # scrolbar for above textarea > sb = Scrollbar(root) > sb.pack(side="right", fill="y") > > > > ## bind them both together... > > # this line binds the yscrollcommand > # of the text area to the scrollbar set method > text['yscrollcommand'] = sb.set > > # this line binds the scrollbars command to > # the yview method of the text area > sb['command'] = text.yview > > > > # mainloop entry > root.mainloop() That doesn't help. I need to be able to do it either with a frame (has content!) or a Text widget. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Scrollbar not working
Label Widget, sorry -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Scrollbar not working
Yes, I know PMW has scrolled Text, but the module has to be installed seperately; this is something I'm releasing to a number of people. I'll try doing it with a canvas. -- http://mail.python.org/mailman/listinfo/python-list
Help Dialogue
How do I make a help dialogue, like the one seen in IDLE when you go to Help-IDLE Help? -- http://mail.python.org/mailman/listinfo/python-list
Limitting the Contents of an Entry Widget in Tkinter
How do I limit what the user can enter in an Entry Widget? I know I can set it to display '*' to hide a password, but what I want to do is limit the contents to numeric characters. What is the easiest way of doing this? -- http://mail.python.org/mailman/listinfo/python-list
Re: random shuffles
Boris Borcic wrote: > does > > x.sort(cmp = lambda x,y : cmp(random.random(),0.5)) > > pick a random shuffle of x with uniform distribution ? > > Intuitively, assuming list.sort() does a minimal number of comparisons to > achieve the sort, I'd say the answer is yes. But I don't feel quite > confortable > with the intuition... can anyone think of a more solid argumentation ? Why not use the supplied shuffle method? random.shuffle(x) -- http://mail.python.org/mailman/listinfo/python-list
Grail not downloading
Does anybody know anything about Grail? I've been unable to get at it, and I've tried on both Windows and Macintosh machines. http://grail.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Grail not downloading
SuperHik wrote: > Dustan wrote: > > Does anybody know anything about Grail? I've been unable to get at > > it, and I've tried on both Windows and Macintosh machines. > > > > http://grail.sourceforge.net/ > > > > http://prdownloads.sourceforge.net/grail/grail-0.6.tgz?download Thanks. I'll try that as soon as I get on a Mac. -- http://mail.python.org/mailman/listinfo/python-list
Re: Grail not downloading
Martin v. Löwis wrote: > Dustan wrote: > > Does anybody know anything about Grail? I've been unable to get at > > it, and I've tried on both Windows and Macintosh machines. > > > > http://grail.sourceforge.net/ > > The files just don't exist, physically, on the server (if you have > an SF account, you can check this yourself). However, it appears > that the source code is still available through CVS: > > http://grail.cvs.sourceforge.net/grail/grail/ > > Regards, > Martin I appreciate the info. I couldn't exactly attempt to download the files manually, though. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Small problem with print and comma
Dennis Lee Bieber wrote: > > for i in range(0,len(param)): > > print a[i], > > for it in param: > print it, That's one way. However, if you need the position (this is for future reference; you don't need the position number here): for i in range(len(param)+1): print a[i], The last position was excluded because you forgot the '+1' part, creating an off-by-one bug. -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested if and expected an indent block
> Thanks for the replies: > > I'm sorry, the colon is there in the original, I accidentally blew it > off when I added the comment. The only information I get from IDLE is a > dialog box that says: > > Syntax Error > There's an error in your program: > expected an indented block > > Keith To see the full traceback, assuming you're using windows, you need to run it on the Command prompt. -- http://mail.python.org/mailman/listinfo/python-list
Long Tkinter Menu
I don't know if this is because of Tkinter (ie Tk) itself or the Windows default way of handling things, but when I create a very long menu (my test is shown below), the way it displays is rather sucky; the menu stretches from the top of the moniter's window to the bottom (no matter the size of the actual application). Is there any alternative format for how a long menu gets displayed? It would be nice if say, I could make the menu only go to the borders of the application itself (in this case, not that long). As for why I'm creating such a long menu, think browser bookmarks (That's not actually what I'm doing, but similar). # menu-example-5.py from Tkinter import * root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0) for i in xrange(100): menu.add_command(label=str(i), command=root.quit) menu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="Test", menu=menu) root.config(menu=menubar) mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Long Tkinter Menu
Eric Brunel wrote:
> On Thu, 05 Oct 2006 02:33:54 +0200, Dustan <[EMAIL PROTECTED]> wrote:
>
> > I don't know if this is because of Tkinter (ie Tk) itself or the
> > Windows default way of handling things, but when I create a very long
> > menu (my test is shown below), the way it displays is rather sucky; the
> > menu stretches from the top of the moniter's window to the bottom (no
> > matter the size of the actual application).
> >
> > Is there any alternative format for how a long menu gets displayed? It
> > would be nice if say, I could make the menu only go to the borders of
> > the application itself (in this case, not that long).
>
> To limit the menu in the application window, will be difficult. But here
> are two ways of automatically limiting the number of entries that can
> appear in a menu by specializing the Tkinter Menu class:
>
> --
> from Tkinter import *
>
> class LongMenu(Menu):
>"""
>Automatically creates a cascade entry labelled 'More...' when the
>number of entries is above MAX_ENTRIES.
>"""
>
>MAX_ENTRIES = 20
>
>def __init__(self, *args, **options):
> Menu.__init__(self, *args, **options)
> self.nextMenu = None
>
>def add(self, itemType, cnf={}, **kw):
> if self.nextMenu is not None:
>return self.nextMenu.add(itemType, cnf, **kw)
> nbEntries = self.index(END)
> if nbEntries < LongMenu.MAX_ENTRIES:
>return Menu.add(self, itemType, cnf, **kw)
> self.nextMenu = LongMenu(self)
> Menu.add(self, 'cascade', label='More...', menu=self.nextMenu)
> return self.nextMenu.add(itemType, cnf, **kw)
>
>
> class AutoBreakMenu(Menu):
>"""
>Automatically adds the 'columnbreak' option on menu entries to make
>sure that the menu won't get too high.
>"""
>
>MAX_ENTRIES = 20
>
>def add(self, itemType, cnf={}, **kw):
> entryIndex = 1 + (self.index(END) or 0)
> if entryIndex % AutoBreakMenu.MAX_ENTRIES == 0:
>cnf.update(kw)
>cnf['columnbreak'] = 1
>kw = {}
> return Menu.add(self, itemType, cnf, **kw)
>
>
>
> if __name__ == '__main__':
>root = Tk()
>
>menubar = Menu(root)
>
>def fillMenu(menu):
> for i in xrange(100):
>menu.add_command(label=str(i), command=root.quit)
> menu.add_command(label="Exit", command=root.quit)
>
>menu1 = LongMenu(menubar, tearoff=0)
>fillMenu(menu1)
>menu2 = AutoBreakMenu(menubar, tearoff=0)
>fillMenu(menu2)
>
>menubar.add_cascade(label="Test1", menu=menu1)
>menubar.add_cascade(label="Test2", menu=menu2)
>
>root.config(menu=menubar)
>
>root.mainloop()
> --
>
> If your application is more complicated than that (e.g if you insert menu
> entries after the first adds), you'll have to change the code above a bit,
> since it doesn't handle calls to insert at all. But you get the idea.
>
> HTH
> --
> python -c "print ''.join([chr(154 - ord(c)) for c in
> 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
Thanks, I'll see what I can do with that.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Strange sorting error message
Steve Holden wrote: > Dustan wrote: > > I'm hiding some of the details here, because I don't want to say what > > I'm actually doing. > > [...] > > I have the answer to your problem but I don't actually want to tell you > what it is. That's great, seeing as I already figured out the answer, as I have already posted in a reply. Are you saying I broke one of these rules? http://www.catb.org/~esr/faqs/smart-questions.html Or are you just being plain rude? A lack of a response from you implies the latter... > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange sorting error message
Neil Cerutti wrote: > On 2006-10-05, Dustan <[EMAIL PROTECTED]> wrote: > > > > Steve Holden wrote: > >> Dustan wrote: > >> > I'm hiding some of the details here, because I don't want to > >> > say what I'm actually doing. > >> > [...] > >> > >> I have the answer to your problem but I don't actually want to > >> tell you what it is. > > > > That's great, seeing as I already figured out the answer, as I > > have already posted in a reply. > > I had a good laugh at it. > > > Are you saying I broke one of these rules? > > http://www.catb.org/~esr/faqs/smart-questions.html > > Or are you just being plain rude? > > A lack of a response from you implies the latter... > > SPOILER SPACE > > It was a joke, based on you hiding what you are doing, he decided > to hide the solution to your problem. Get it? Ah, now I get it... Well, not really. I'm not outgoing, so it's hard for me to spot a joke when I see one. > > -- > Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Reverse string-formatting (maybe?)
Is there any builtin function or module with a function similar to my
made-up, not-written deformat function as follows? I can't imagine it
would be too easy to write, but possible...
>>> template = 'I am %s, and he %s last %s.'
>>> values = ('coding', "coded', 'week')
>>> formatted = template % values
>>> formatted
'I am coding, and he coded last week.'
>>> deformat(formatted, template)
('coding', 'coded', 'week')
expanded (for better visual):
>>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s last
>>> %s.')
('coding', 'coded', 'week')
It would return a tuple of strings, since it has no way of telling what
the original type of each item was.
Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reverse string-formatting (maybe?)
Peter Otten wrote:
> Dustan wrote:
>
> > Is there any builtin function or module with a function similar to my
> > made-up, not-written deformat function as follows? I can't imagine it
> > would be too easy to write, but possible...
> >
> >>>> template = 'I am %s, and he %s last %s.'
> >>>> values = ('coding', "coded', 'week')
> >>>> formatted = template % values
> >>>> formatted
> > 'I am coding, and he coded last week.'
> >>>> deformat(formatted, template)
> > ('coding', 'coded', 'week')
> >
> > expanded (for better visual):
> >>>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s
> >>>> last %s.')
> > ('coding', 'coded', 'week')
> >
> > It would return a tuple of strings, since it has no way of telling what
> > the original type of each item was.
> >
> >
> > Any input? I've looked through the documentation of the string module
> > and re module, did a search of the documentation and a search of this
> > group, and come up empty-handed.
>
> Simple, but unreliable:
>
> >>> import re
> >>> template = "I am %s, and he %s last %s."
> >>> values = ("coding", "coded", "week")
> >>> formatted = template % values
> >>> def deformat(formatted, template):
> ... r = re.compile("(.*)".join(template.split("%s")))
> ... return r.match(formatted).groups()
> ...
> >>> deformat(formatted, template)
> ('coding', 'coded', 'week')
>
> Peter
Trying to figure out the 'unreliable' part of your statement...
I'm sure 2 '%s' characters in a row would be a bad idea, and if you
have similar expressions for the '%s' characters within as well as in
the neighborhood of the '%s', that would cause difficulty. Is there any
other reason it might not work properly?
My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reverse string-formatting (maybe?)
Tim Chase wrote:
> > My template outside of the '%s' characters contains only commas and
> > spaces, and within, neither commas nor spaces. Given that information,
> > is there any reason it might not work properly?
>
> Given this new (key) information along with the assumption that
> you're doing straight string replacement (not dictionary
> replacement of the form "%(key)s" or other non-string types such
> as "%05.2f"), then yes, a reversal is possible. To make it more
> explicit, one would do something like
>
> >>> template = '%s, %s, %s'
> >>> values = ('Tom', 'Dick', 'Harry')
> >>> formatted = template % values
> >>> import re
> >>> unformat_string = template.replace('%s', '([^, ]+)')
> >>> unformatter = re.compile(unformat_string)
> >>> extracted_values = unformatter.search(formatted).groups()
>
> using '[^, ]+' to mean "one or more characters that aren't a
> comma or a space".
>
> -tkc
Thanks.
One more thing (I forgot to mention this other situation earlier)
The %s characters are ints, and outside can be anything except int
characters. I do have one situation of '%s%s%s', but I can change it to
'%s', and change the output into the needed output, so that's not
important. Think something along the lines of "abckdaldj iweo%s
qwierxcnv !%sjd".
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reverse string-formatting (maybe?)
Dustan wrote:
> Tim Chase wrote:
> > > My template outside of the '%s' characters contains only commas and
> > > spaces, and within, neither commas nor spaces. Given that information,
> > > is there any reason it might not work properly?
> >
> > Given this new (key) information along with the assumption that
> > you're doing straight string replacement (not dictionary
> > replacement of the form "%(key)s" or other non-string types such
> > as "%05.2f"), then yes, a reversal is possible. To make it more
> > explicit, one would do something like
> >
> > >>> template = '%s, %s, %s'
> > >>> values = ('Tom', 'Dick', 'Harry')
> > >>> formatted = template % values
> > >>> import re
> > >>> unformat_string = template.replace('%s', '([^, ]+)')
> > >>> unformatter = re.compile(unformat_string)
> > >>> extracted_values = unformatter.search(formatted).groups()
> >
> > using '[^, ]+' to mean "one or more characters that aren't a
> > comma or a space".
> >
> > -tkc
>
> Thanks.
>
> One more thing (I forgot to mention this other situation earlier)
> The %s characters are ints, and outside can be anything except int
> characters. I do have one situation of '%s%s%s', but I can change it to
> '%s', and change the output into the needed output, so that's not
> important. Think something along the lines of "abckdaldj iweo%s
> qwierxcnv !%sjd".
That was written in haste. All the information is true. The question:
I've already created a function to do this, using your original
deformat function. Is there any way in which it might go wrong?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reverse string-formatting (maybe?)
Dustan wrote:
> Dustan wrote:
> > Tim Chase wrote:
> > > > My template outside of the '%s' characters contains only commas and
> > > > spaces, and within, neither commas nor spaces. Given that information,
> > > > is there any reason it might not work properly?
> > >
> > > Given this new (key) information along with the assumption that
> > > you're doing straight string replacement (not dictionary
> > > replacement of the form "%(key)s" or other non-string types such
> > > as "%05.2f"), then yes, a reversal is possible. To make it more
> > > explicit, one would do something like
> > >
> > > >>> template = '%s, %s, %s'
> > > >>> values = ('Tom', 'Dick', 'Harry')
> > > >>> formatted = template % values
> > > >>> import re
> > > >>> unformat_string = template.replace('%s', '([^, ]+)')
> > > >>> unformatter = re.compile(unformat_string)
> > > >>> extracted_values = unformatter.search(formatted).groups()
> > >
> > > using '[^, ]+' to mean "one or more characters that aren't a
> > > comma or a space".
> > >
> > > -tkc
> >
> > Thanks.
> >
> > One more thing (I forgot to mention this other situation earlier)
> > The %s characters are ints, and outside can be anything except int
> > characters. I do have one situation of '%s%s%s', but I can change it to
> > '%s', and change the output into the needed output, so that's not
> > important. Think something along the lines of "abckdaldj iweo%s
> > qwierxcnv !%sjd".
>
> That was written in haste. All the information is true. The question:
> I've already created a function to do this, using your original
> deformat function. Is there any way in which it might go wrong?
Again, haste. I used Peter's deformat function.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reverse string-formatting (maybe?)
> Only you know what anomalies will be found in your data-sets. If
> you know/assert that
>
> -the only stuff in the formatting string is one set of characters
>
> -that stuff in the replacement-values can never include any of
> your format-string characters
>
> -that you're not using funky characters/formatting in your format
> string (such as "%%" possibly followed by an "s" to get the
> resulting text of "%s" after formatting, or trying to use other
> formatters such as the aforementioned "%f" or possibly "%i")
>
> then you should be safe. It could also be possible (with my
> original replacement of "(.*)") if your values will never include
> any substring of your format string. If you can't guarantee
> these conditions, you're trying to make a cow out of hamburger.
> Or a pig out of sausage. Or a whatever out of a hotdog. :)
>
> Conventional wisdom would tell you to create a test-suite of
> format-strings and sample values (preferably worst-case funkiness
> in your expected format-strings/values), and then have a test
> function that will assert that the unformatting of every
> formatted string in the set returns the same set of values that
> went in. Something like
>
> tests = {
> 'I was %s but now I am %s' : [
> ('hot', 'cold'),
> ('young', 'old'),
> ],
> 'He has 3 %s and 2 %s' : [
> ('brothers', 'sisters'),
> ('cats', 'dogs')
> ]
> }
>
> for format_string, values in tests:
> unformatter = format.replace('%s', '(.*)')
> for value_tuple in values:
> formatted = format_string % value_tuple
> unformatted = unformatter.search(formatted).groups()
> if unformatted <> value_tuple:
> print "%s doesn't match %s when unformatting %s" % (
> unformatted,
> value_tuple
> format_string)
>
> -tkc
Thanks for all your help. I've gotten the idea.
--
http://mail.python.org/mailman/listinfo/python-list
Inheriting property functions
Looking at this interactive session: >>> class A(object): def __init__(self, a): self.a = a def get_a(self): return self.__a def set_a(self, new_a): self.__a = new_a a = property(get_a, set_a) >>> class B(A): b = property(get_a, set_a) Traceback (most recent call last): File "", line 1, in class B(A): File "", line 2, in B b = property(get_a, set_a) NameError: name 'get_a' is not defined >>> class B(A): b = a Traceback (most recent call last): File "", line 1, in class B(A): File "", line 2, in B b = a NameError: name 'a' is not defined >>> B isn't recognizing its inheritence of A's methods get_a and set_a during creation. Why am I doing this? For an object of type B, it makes more sense to reference the attribute 'b' than it does to reference the attribute 'a', even though they are the same, in terms of readability. Is there any way to make this work as intended? -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheriting property functions
Dustan wrote: > Looking at this interactive session: > > >>> class A(object): > def __init__(self, a): > self.a = a > def get_a(self): return self.__a > def set_a(self, new_a): self.__a = new_a > a = property(get_a, set_a) > > > >>> class B(A): > b = property(get_a, set_a) > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = property(get_a, set_a) > NameError: name 'get_a' is not defined > >>> class B(A): > b = a > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = a > NameError: name 'a' is not defined > >>> > > B isn't recognizing its inheritence of A's methods get_a and set_a > during creation. > > Why am I doing this? For an object of type B, it makes more sense to > reference the attribute 'b' than it does to reference the attribute > 'a', even though they are the same, in terms of readability. Clarification: The code given is obviously not the actual code. I doubt it would really make a difference in types A and B given here, but for what I'm actually doing, it makes a big difference. > Is there any way to make this work as intended? -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheriting property functions
Robert Kern wrote: > Dustan wrote: > > Looking at this interactive session: > > > >>>> class A(object): > > def __init__(self, a): > > self.a = a > > def get_a(self): return self.__a > > def set_a(self, new_a): self.__a = new_a > > a = property(get_a, set_a) > > > > > >>>> class B(A): > > b = property(get_a, set_a) > > > > > > Traceback (most recent call last): > > File "", line 1, in > > class B(A): > > File "", line 2, in B > > b = property(get_a, set_a) > > NameError: name 'get_a' is not defined > >>>> class B(A): > > b = a > > > > > > Traceback (most recent call last): > > File "", line 1, in > > class B(A): > > File "", line 2, in B > > b = a > > NameError: name 'a' is not defined > > > > B isn't recognizing its inheritence of A's methods get_a and set_a > > during creation. > > Inheritance really doesn't work that way. The code in the class suite gets > executed in its own namespace that doesn't know anything about inheritance. > The > inheritance rules operate in attribute access on the class object later. > > Try this: > >class B(A): > b = property(A.get_a, A.set_a) > > or this: > >class B(A): > b = A.a > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." >-- Umberto Eco Thanks for your help, and mdsteele's. -- http://mail.python.org/mailman/listinfo/python-list
Customize the effect of enumerate()?
Can I make enumerate(myObject) act differently? class A(object): def __getitem__(self, item): if item > 0: return self.sequence[item-1] elif item < 0: return self.sequence[item] elif item == 0: raise IndexError, "Index 0 is not valid." else: raise IndexError, "Invalid Index." def __iter__(self): return iter(self.sequence) Why the funny behavior, you ask? For my class A, it doesn't make sense to number everything the standard programming way. Of course, if someone uses enumerate, it's going to number the items the same way as ever. Is there any way to modify that behavior, any special function to set? There doesn't appear to be, according to the docs, but it never hurts to make sure. -- http://mail.python.org/mailman/listinfo/python-list
Re: Customize the effect of enumerate()?
Paul Rubin wrote: > "Dustan" <[EMAIL PROTECTED]> writes: > > Can I make enumerate(myObject) act differently? > > No. > > > Why the funny behavior, you ask? For my class A, it doesn't make sense > > to number everything the standard programming way. > > Add an enumerate method to the class then, that does what you want. > Maybe dict.iteritems would be a better example to follow. That's what I thought. Thanks anyway! -- http://mail.python.org/mailman/listinfo/python-list
Re: Customize the effect of enumerate()?
Simon Forman wrote: > Dustan wrote: > > Can I make enumerate(myObject) act differently? > > > > class A(object): > > def __getitem__(self, item): > > if item > 0: > > return self.sequence[item-1] > > elif item < 0: > > return self.sequence[item] > > elif item == 0: > > raise IndexError, "Index 0 is not valid." > > else: > > raise IndexError, "Invalid Index." > > def __iter__(self): return iter(self.sequence) > > That final else clause is a little funny...What kind of indices are > you expecting that will be neither less than zero, greater than zero, > or equal to zero? I'm not 'expecting' anything to reach that clause, but it is a good catch-all if I forget something or have a bug somewhere. > > Why the funny behavior, you ask? For my class A, it doesn't make sense > > to number everything the standard programming way. Of course, if > > someone uses enumerate, it's going to number the items the same way as > > ever. Is there any way to modify that behavior, any special function to > > set? There doesn't appear to be, according to the docs, but it never > > hurts to make sure. > > You can write your own enumerate function and then bind that to the > name 'enumerate'. Except that my program is supposed to be treated as a module with tools to do certain things. I certainly can't control whether a 3rd party programmer uses "import myModule" or "from myModule import *". I haven't gotten around to doing it yet, but I'm pretty sure I'm planning on taking Paul Rubin's course of action - make a method (iteritems or similar) that will enumerate correctly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Customize the effect of enumerate()?
Fredrik Lundh wrote:
> "Dustan" wrote:
>
> > Except that my program is supposed to be treated as a module with tools
> > to do certain things. I certainly can't control whether a 3rd party
> > programmer uses "import myModule" or "from myModule import *".
>
> anything can happen if people use "from import *" in the wrong way, so that's
> not much of an argument, really.
>
>
My argument was that if they use "import myModule", overriding
enumerate() wouldn't work. So "from myModule import *" would work
nicely, but not the former. Given that, I'm not getting your rebuttal,
or whatever it is.
Steven D'Aprano wrote:
> On Sun, 22 Oct 2006 15:56:16 -0700, Simon Forman wrote:
> > That final else clause is a little funny...What kind of indices are
> > you expecting that will be neither less than zero, greater than zero,
> > or equal to zero?
>
> Possible a NaN value? Maybe a class instance with strange comparison
> methods?
>
> Personally, I don't like the error message. "Invalid index" doesn't really
> tell the caller what went wrong and why it is an invalid index. If I were
> programming that defensively, I'd write:
>
> if item > 0:
> return self.sequence[item-1]
> elif item < 0:
> return self.sequence[item]
> elif item == 0:
> raise IndexError, "Index 0 is not valid."
> else:
> print repr(item)
> raise ThisCanNeverHappenError("Congratulations! You've discovered "
> "a bug that can't possibly occur. Contact the program author for "
> "your reward.")
>
> I know some programmers hate "Can't happen" tests and error messages, but
> if you are going to test for events that can't possibly happen, at least
> deal with the impossible explicitly!
I certainly can't argue with that logic; I might even go so far as to
agree with you and start raising impossible errors with this kind of
explicitness.
What reward should I offer? ;-)
--
http://mail.python.org/mailman/listinfo/python-list
disabledforeground or similar for Entry (in Tkinter)
Back in this post, I attempted to make a label look like a button: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a83195d3970a6851/2053cbaec1bc1f19?auth=DQAAAHkMDAWnhNnzpuKlwOKZUwAGUTtT2Ay-EAB7rCY6SnwfnDzZ98M37bZDW2Is0LrBVrr8XEgPfcuOkiUE-CrSsKbBSX-67voDUXfbATBd0eYNMClezby4EXT2fuLm6f0llJ_xMO8BfkjVho_7CZvlf_9tNGnJixTbq8zr21ODZBhouQ Alright, I've learned my lesson - don't use a new widget; modify the old one. Except the Entry widget doesn't have a disabledforeground option. Neither does the Text widget, but IDLE seems to accomplish making a disabled Text look the same as an enabled Text in the IDLE Help section. No, foreground (fg) and background (bg) don't make a difference; it still changes the color of the Entry widget upon disabling. There must be something I'm missing here... -- http://mail.python.org/mailman/listinfo/python-list
Re: disabledforeground or similar for Entry (in Tkinter)
Dustan wrote: > Back in this post, I attempted to make a label look like a button: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/a83195d3970a6851/2053cbaec1bc1f19?auth=DQAAAHkMDAWnhNnzpuKlwOKZUwAGUTtT2Ay-EAB7rCY6SnwfnDzZ98M37bZDW2Is0LrBVrr8XEgPfcuOkiUE-CrSsKbBSX-67voDUXfbATBd0eYNMClezby4EXT2fuLm6f0llJ_xMO8BfkjVho_7CZvlf_9tNGnJixTbq8zr21ODZBhouQ > > Alright, I've learned my lesson - don't use a new widget; modify the > old one. > > Except the Entry widget doesn't have a disabledforeground option. > Neither does the Text widget, but IDLE seems to accomplish making a > disabled Text look the same as an enabled Text in the IDLE Help > section. > > No, foreground (fg) and background (bg) don't make a difference; it > still changes the color of the Entry widget upon disabling. > > There must be something I'm missing here... Yes there is! I assumed that http://www.pythonware.com/library/tkinter/introduction/x4447-options.htm was telling the truth, in that it's not listed there. -- http://mail.python.org/mailman/listinfo/python-list
reduce to be removed?
According to the following page on Wikipedia: http://en.wikipedia.org/wiki/Python_%28programming_language%29#Future_development reduce is going to be removed in python 3.0. It talks of an accumulation loop; I have no idea what that's supposed to mean. So, === >>> x =\ [[1,2,3], [4,5,6], [7,8,9]] >>> reduce(lambda a,b:a+b, x, []) [1, 2, 3, 4, 5, 6, 7, 8, 9] === What's an accumulation loop, and how would I convert this code so it's compatible with the future 3.0 (preferably in a short sweet expression that I can embed in a list comprehension)? -- http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
Fredrik Lundh wrote:
> Dustan wrote:
>
> > What's an accumulation loop, and how would I convert this code so it's
> > compatible with the future 3.0
>
> the release of Python 3.0 is far away, and nobody knows how it's going
> to look. trying to be future-compatible at this time is a major waste
> of time and (not quite as wasteful as reopening yet another old "let's
> make some pointless change to the language" thread, but almost).
>
> surely you must have something better to do with your time ?
>
>
It's always nice to know there are such good-natured people ready to
help on this group. Anyway, I figured out a way to get the builtin
function 'sum' to work as I need:
sum([[1,2,3],[4,5,6],[7,8,9]], [])
On an unrelated note, can anyone explain this unpredictable behavior on
IDLE? I swear I never hit ctrl-c...
==
>>> help(sum)
Help on built-in function sum in module __builtin__:
sum(...)
sum(sequence, start=0) -> value
Returns the sum of a sequence of numbers (NOT strings) plus the
value
of parameter 'start'. When the sequence is empty, returns start.
Traceback (most recent call last):
File "", line 1, in
help(sum)
File "C:\Python25\lib\site.py", line 346, in __call__
return pydoc.help(*args, **kwds)
File "C:\Python25\lib\pydoc.py", line 1642, in __call__
self.help(request)
File "C:\Python25\lib\pydoc.py", line 1687, in help
self.output.write('\n')
File "C:\Python25\lib\idlelib\PyShell.py", line 1246, in write
self.shell.write(s, self.tags)
File "C:\Python25\lib\idlelib\PyShell.py", line 1235, in write
raise KeyboardInterrupt
KeyboardInterrupt
==
--
http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
Fredrik Lundh wrote: > Dustan wrote: > > > It's always nice to know there are such good-natured people ready to > > help on this group. > > any special reason why you keep pretending that some random wikipedia > editor knows more about a future Python release than the people that > develops Python ? Be careful how you word that - this is the first time I've ever referenced wikipedia in a question on this forum. > > Anyway, I figured out a way to get the builtin > > function 'sum' to work as I need: > > sum([[1,2,3],[4,5,6],[7,8,9]], []) > > sum() is designed for adding numbers, not sequences. abusing it > for sequences leads to inefficient code, and extremely bad worst- > case behaviour, since you end up copying the same data over and > over and over again Thanks for some quality feedback for a change. Why can't you do that more often? > -- the function even checks for strings for > this very reason: > > >>> sum(["123", "456", "789"], "") > Traceback (most recent call last): >File "", line 1, in ? > TypeError: sum() can't sum strings [use ''.join(seq) instead] > > (maybe it should check for other well-known containers as well?) > > if you care about writing robust code, why not just use a for-loop, > and the list extend method? Because I'm embedding this expression in a list comprehension (as I stated in my original post), and last time I checked, it's not possible to treat a for-loop as an expression (which is what a list comprehension requires). > -- http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
Fredrik Lundh wrote: > Dustan wrote: > > > Because I'm embedding this expression in a list comprehension > > because? > > Because I thought I would be able to get an answer without revealing the exact details of what I am doing. I didn't realize that wasn't an option. I'll try once more to give you an idea of what I'm trying to accomplish without letting on the details. >>> foo =\ [[[1,2,3],[4,5,6],[7,8,9]], [[3,2,1],[6,5,4],[9,8,7]]] Here, foo appears to be a 3-dimensional list - except it's supposed to be 2-dimensional. The inner-list-of-lists is a result of how I'm producing the data, and now I want to do a mass-concatenation (or extending) of the inner-list-of-lists, and come up with this: >>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]] True What's the best way to accomplish this? It's not quite this simple, but let's just see what you can come up with the information at hand, and I'll see if I can adapt it to my needs. -- http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
Fredrik Lundh wrote: > Dustan wrote: > > >> > Because I'm embedding this expression in a list comprehension > >> > >> because? > > > > Because I thought I would be able to get an answer without revealing > > the exact details of what I am doing. > > alright, let's try again: why do you need a self-contained reduce > replacement that can be embedded inside a list comprehension ? > > >>> foo =\ [[[1,2,3],[4,5,6],[7,8,9]], [[3,2,1],[6,5,4],[9,8,7]]] Here, foo appears to be a 3-dimensional list - except it's supposed to be 2-dimensional. The inner-list-of-lists is a result of how I'm producing the data, and now I want to do a mass-concatenation (or extending) of the inner-list-of-lists, and come up with this result: >>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]] True What's the best way to accomplish this? It's not quite this simple, but let's just see what you can come up with the information at hand, and I'll see if I can adapt it to my needs. -- http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
Robert Kern wrote: > Dustan wrote: > > Fredrik Lundh wrote: > > >> if you care about writing robust code, why not just use a for-loop, > >> and the list extend method? > > > > Because I'm embedding this expression in a list comprehension (as I > > stated in my original post), and last time I checked, it's not possible > > to treat a for-loop as an expression (which is what a list > > comprehension requires). > > As with all such things, you stick the implementation in a well-named function > and simply call the function everywhere. The implementation never needs to be > a > one-liner expression. It's already in a function, but in order to convert the reduce function into a for-loop that I can use as an expression, I would have to create another independent function, which would make that code more cluttered than it already is. Unless you're saying to perform the list comprehension manually. That would be two for-loops I use in the list comprehension, plus another one to take place of the reduce function. Sure, that spreads out each individual step a little more, but it also makes it more difficult to understand what the overall goal of the code is (I'm going for readability as well as easy maintenance here). > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
Fredrik Lundh wrote: > Dustan wrote: > > >>>> foo =\ > > [[[1,2,3],[4,5,6],[7,8,9]], > > [[3,2,1],[6,5,4],[9,8,7]]] > > > > Here, foo appears to be a 3-dimensional list - except it's supposed to > > be 2-dimensional. The inner-list-of-lists is a result of how I'm > > producing the data, and now I want to do a mass-concatenation (or > > extending) of the inner-list-of-lists, and come up with this result: > > > >>>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]] > > True > > that still doesn't explain your "the expression must be used in a list > comprehension" requirement, though. Oh, right; sorry about the confusion. The list isn't quite that simple, and in order to pull the right pieces together, I use a list comprehension. > assuming that the sizes are > varying, and at least sometimes a lot larger than 3x3, I'd probably > write the above as > > for index, item in enumerate(foo): > this = [] > for i in item: > this.extend(i) > foo[index] = this I'll see if that works. > which should be pretty efficient, since it avoids unnecessary function > calls, and is amortized linear time instead of O(N**2). > > or, if I was in a hurry, and didn't really care if the inner sequences > were lists or tuples: > > foo = map(Tkinter._flatten, foo) > > Steven D'Aprano wrote: > I don't know if this is the best, but it didn't take long to come up with > it: > > >>> foo = [[[1,2,3],[4,5,6],[7,8,9]], > ... [[3,2,1],[6,5,4],[9,8,7]]] > >>> > >>> def unroll(list3d): > ... newl = [] > ... for sublist in list3d: > ... newl.append(sum(sublist, [])) > ... return newl deja vu... > >>> bar = unroll(foo) > >>> bar > [[1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 2, 1, 6, 5, 4, 9, 8, 7]] > > > Repeat after me: > > "Not everything has to be a one-liner." Not everything has to be a one-liner. But readability helps. > If sum() is too slow, because your sub-lists are huge, you can easily > factor that out and replace it with something using extend. > > > -- > Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
Alright, I can see I'm a bit outvoted here. I tried your suggestions and it worked fine. I'll also try to consider in the future that part of the problem might be lack of information conveyed on my part. -- http://mail.python.org/mailman/listinfo/python-list
Re: reduce to be removed?
George Sakkis wrote: > Dustan wrote: > > > Alright, I can see I'm a bit outvoted here. I tried your suggestions > > and it worked fine. > > > > I'll also try to consider in the future that part of the problem might > > be lack of information conveyed on my part. > > If you insist on one-liners, it can be done without sum(), though it > probably doesn't buy you much in readability: > > from itertools import chain > [list(chain(*row)) for row in foo] > > By the way, if this was not a toy example and you're doing serious work > with n-dimensional arrays, make yourself a favor and install NumPy; > it's usually both faster and more elegant for array manipulations than > pure python. 1. I've already written pretty much all the code, and a complete rewrite would be rather difficult. 2. While I haven't taken a good look at NumPy, my intuition tells me it won't work with complex data types, which wouldn't work for me at all. Am I correct on that second one? -- http://mail.python.org/mailman/listinfo/python-list
Downloading and Displaying an Image from the Internet in Tkinter
The title pretty much says it all. What is the easiest way in Tkinter to display an image from the internet given the URL? -- http://mail.python.org/mailman/listinfo/python-list
Again, Downloading and Displaying an Image from the Internet in Tkinter
Nobody answered last time. I guess they wanted me to give it a shot.
Well, here is how I download the image (it's a class method):
def download_image(self):
web_download=self.opener.open(self.url)
save=open("image.jpg","w")
save.writelines(web_download.readlines())
save.close()
web_download.close()
self.opener is urllib.URLopener(), self.url is the url for the image.
I display the image as follows:
self.image=t.Label(self.frame,image=path+"\\image.jpg")
t is Tkinter, path is sys.path[0].
(if sys.path[0] is not the proper way of getting the program's path,
inform me; I hunted it down without any reference to look to)
But the image won't display, using any application (including Tkinter,
paint, Firefox, etc.). I'm assuming the reason it can't be read is
because the image is protected from downloading.
So, once again, is there a better way to download and display an image
using Tkinter?
Did I try hard enough for you? Are you going to help me this time?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Again, Downloading and Displaying an Image from the Internet in Tkinter
I wrote:
> Nobody answered last time. I guess they wanted me to give it a shot.
> Well, here is how I download the image (it's a class method):
>
> def download_image(self):
> web_download=self.opener.open(self.url)
> save=open("image.jpg","w")
> save.writelines(web_download.readlines())
> save.close()
> web_download.close()
>
> self.opener is urllib.URLopener(), self.url is the url for the image.
>
> I display the image as follows:
>
> self.image=t.Label(self.frame,image=path+"\\image.jpg")
>
> t is Tkinter, path is sys.path[0].
> (if sys.path[0] is not the proper way of getting the program's path,
> inform me; I hunted it down without any reference to look to)
>
>
> But the image won't display, using any application (including Tkinter,
> paint, Firefox, etc.). I'm assuming the reason it can't be read is
> because the image is protected from downloading.
>
> So, once again, is there a better way to download and display an image
> using Tkinter?
>
> Did I try hard enough for you? Are you going to help me this time?
I should probably also mention, the only reason I downloaded the image
to a file was because I don't know of any other way to do it. I feel no
need to save the image to my hard drive.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Again, Downloading and Displaying an Image from the Internet in Tkinter
Justin Ezequiel wrote:
> cannot help you with Tkinter but...
>
> save=open("image.jpg","wb")
> save.write(web_download.read())
> save.close()
>
> perhaps this would let you open the file in Paint
Ok, that worked (was it plain w or the writelines/readlines that messed
it up?). But Tkinter still can't find the image. I'm getting an error
message:
TclError: image "C:\Documents and [pathname snipped]" doesn't exist
If it makes a difference, I'm on a Windows XP machine, and don't have
to go cross-platform.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Again, Downloading and Displaying an Image from the Internet in Tkinter
Fredrik Lundh wrote: > Dustan wrote: > > > Ok, that worked (was it plain w or the writelines/readlines that messed > > it up?). > > the plain "w"; very few image files are text files. > > > But Tkinter still can't find the image. I'm getting an error > > message: > > > > TclError: image "C:\Documents and [pathname snipped]" doesn't exist > > > > If it makes a difference, I'm on a Windows XP machine, and don't have > > to go cross-platform. > > the "image" option takes a PhotoImage object, not a file name: > > http://effbot.org/tkinterbook/photoimage.htm > > note that the built-in PhotoImage type only supports a few image > formats; to get support for e.g. PNG and JPEG, you can use PIL which > ships with it's own PhotoImage replacement: > > http://effbot.org/imagingbook/imagetk.htm Thanks for the information. The reason I hadn't made any attempt before is well illustrated here; I didn't have enough information at my disposal to know where to start and how I it works. My references are more basic-level than that (I do have a better reference to look to, but it's currently inaccessible). -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing again and again
abcd wrote: > If I have code which imports a module over and over again...say each > time a function is called, does that cause Python to actually re-import > it...or will it skip it once the module has been imported?? > > for example: > > def foo(): > import bar > bar.printStuff() > > foo() > foo() > foo() > foo() > > ...will that re-import bar 4 times...or just import it once? is this a > big performance hit? > > thanks I don't really know, but I do know that the right way to re-import a module is: reload(bar) -- http://mail.python.org/mailman/listinfo/python-list
Making a Label that looks the same as a button.
I have a Button object that gets replaced by a Label when clicked. Button(buttonsframe,text=' ',command=c,font=buttonsFont) Note that the text is a single space. buttonsFont uses 'Courier New' as a family. When clicked, the Button is destroyed and replaced with a Label object: Label(buttonsframe,text=x,font=buttonsFont,relief=RAISED) The intent is for the Label object to look identical to the button object, except for the non-space character x. The Label object is a little smaller than the Button object. When I set borderwidth, the label object does increase in size, but that's not going to make it look the same, since it makes the border thicker. How do I get the Label object to look just like the Button object? -- http://mail.python.org/mailman/listinfo/python-list
Re: Making a Label that looks the same as a button.
Cameron Laird wrote: > In article <[EMAIL PROTECTED]>, > Grayson, John <[EMAIL PROTECTED]> wrote: > > > > > > > >Buttons can look like labels without the need to create another object - > >just remove the > >Command binding, set state to DISABLED and disabledforeground='same > >color as NORMAL'... > > > >This demonstrates how to play with button styles: > . > . > . > John, as I read the original poster, Tkinter.DISABLED is *exactly* > what he wants (although he might not realize it yet); I suspect > there's no need at all for other styling. > > Are Button and Label styles truly identical except for > disabledforeground? While I can't make the time now to research > this for myself, it surprises me; I thought there were padding > differences ... > > Your remark about the Command has me curious: why remove it? In > terms of the original poster's description, what does this serve? > I repeat my speculation that Tkinter.DISABLED will "do it all" for > him. Yes, that's what I needed (and I knew about that before), but I didn't know about the disabledforeground option. Thanks for the information; it worked nicely. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter.Button(... command) lambda and argument problem
Jay wrote: > Thanks for the tip, but that breaks things later for what I'm doing. > > [EMAIL PROTECTED] wrote: > > In that case you don't need a lambda: > > > > import Tkinter as tk > > > > class Test: > > def __init__(self, parent): > > buttons = [tk.Button(parent, text=str(x+1), > > command=self.highlight(x)) for x in range(5)] > > for button in buttons: > > button.pack(side=tk.LEFT) Well, actually, that's wrong. You obviously don't understand why lambda is necessary for event binding; in this case (and many others, for that matter), the button gets bound to the event *returned* by self.highlight(x), which, since nothing gets returned, would be None. Then when you click the button, Tkinter calls None(), and out of the blue, an error is raised. Lambda is the safe way around that error. > > > > def highlight(self, x): > > print "highlight", x > > > > root = tk.Tk() > > d = Test(root) > > root.mainloop() > > > > Bye, > > bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter.Button(... command) lambda and argument problem
James Stroud wrote: > Dustan wrote: > > Jay wrote: > > > >>Thanks for the tip, but that breaks things later for what I'm doing. > >> > >>[EMAIL PROTECTED] wrote: > >> > >>>In that case you don't need a lambda: > >>> > >>>import Tkinter as tk > >>> > >>>class Test: > >>>def __init__(self, parent): > >>>buttons = [tk.Button(parent, text=str(x+1), > >>>command=self.highlight(x)) for x in range(5)] > >>>for button in buttons: > >>>button.pack(side=tk.LEFT) > > > > > > Well, actually, that's wrong. You obviously don't understand why lambda > > is necessary for event binding; in this case (and many others, for that > > matter), the button gets bound to the event *returned* by > > self.highlight(x), which, since nothing gets returned, would be None. > > Then when you click the button, Tkinter calls None(), and out of the > > blue, an error is raised. > > > > Lambda is the safe way around that error. > > > > > >>>def highlight(self, x): > >>>print "highlight", x > >>> > >>>root = tk.Tk() > >>>d = Test(root) > >>>root.mainloop() > >>> > >>>Bye, > >>>bearophile > > > > > > Actually, lambda is not necessary for event binding, but a closure (if I > have the vocab correct), is: Of course. What I should have said was "lambda is the quickest and easiest way". However, if you want your intent to be clear, lambda isn't always the best option, but it is quite often the quickest. > > import Tkinter as tk > > def make_it(x): >def highliter(x=x): > print "highlight", x >return highliter > > class Test: > def __init__(self, parent): > buttons = [tk.Button(parent, text=str(x+1), > command=make_it(x)) for x in range(5)] > for button in buttons: > button.pack(side=tk.LEFT) > > root = tk.Tk() > d = Test(root) > root.mainloop() > > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: eval(repr(object)) hardly ever works
Matthew Wilson wrote: > I understand that idea of an object's __repr__ method is to return a > string representation that can then be eval()'d back to life, but it > seems to me that it doesn't always work. > > For example it doesn't work for instances of the object class: > > In [478]: eval(repr(object())) > >File "", line 1 > > ^ > SyntaxError: invalid syntax > > It seems to work for types like integers and dictionaries and lists, > but not for much else. > > Any thoughts? > > > -- > A better way of running series of SAS programs: > http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles You have to write the code to return a proper representation. -- http://mail.python.org/mailman/listinfo/python-list
webbrowser module's Firefox support
At http://docs.python.org/whatsnew/modules.html on the webbrowser
module, it says "A number of additional browsers were added to the
supported list such as Firefox, Opera, Konqueror, and elinks."
I just installed python 2.5, looking forward to being able to control
firefox without having to make it my default browser, but...
I don't seem to have that functionality. In IDLE:
>>> import webbrowser
>>> webbrowser._browsers
{'windows-default': [, None]}
So I tried to track down what the problem might be, seeing as I also
have Netscape installed on my system (Windows XP), and it's not showing
up either. I found where the code appears to test that the system has
firefox installed, and found it calls _iscommand; here's what I get
running similar code:
>>> import os
>>> path = os.environ.get("PATH")
>>> for d in path.split(os.pathsep):
print d
C:\Perl\bin\
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
c:\Python22
C:\Program Files\PC-Doctor for Windows\services
C:\Program Files\Hummingbird\Connectivity\7.10\Accessories\
C:\PROGRA~1\CA\SHARED~1\SCANEN~1
C:\PROGRA~1\CA\ETRUST~1
The path for firefox is "C:\Program Files\Mozilla Firefox\firefox.exe".
Ok, now I'm at a roadblock; I have no idea where to go from here.
I did do a search here, but came up empty-handed. Can anyone tell me
how to get the webbrowser module to recognize firefox's existence,
given this information?
--
http://mail.python.org/mailman/listinfo/python-list
Re: webbrowser module's Firefox support
MonkeeSage wrote:
> Dustan wrote:
> > I did do a search here, but came up empty-handed. Can anyone tell me
> > how to get the webbrowser module to recognize firefox's existence,
> > given this information?
>
> Looks like it is checking %PATH% for firefox.exe. Try:
>
> >>> import os
> >>> os.environ["PATH"] = r"C:\Program Files\Mozilla Firefox;"
> >>> import webbrowser
> >>> webbrowser._browsers
>
> Regards,
> Jordan
Thanks! But I'm still getting an error message:
>>> import webbrowser
>>> webbrowser._browsers
{'windows-default': [, None],
'firefox': [None, ]}
>>> cont=webbrowser._browsers['firefox'][1]
>>> cont
>>> cont.open("http://www.google.com";)
Traceback (most recent call last):
File "", line 1, in
cont.open("http://www.google.com";)
File "C:\Python25\lib\webbrowser.py", line 185, in open
p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid)
File "C:\Python25\lib\subprocess.py", line 551, in __init__
raise ValueError("close_fds is not supported on Windows "
ValueError: close_fds is not supported on Windows platforms
Looking in the docs on subprocess.Popopen
(http://docs.python.org/lib/node529.html), it says "If close_fds is
true, all file descriptors except 0, 1 and 2 will be closed before the
child process is executed. (Unix only)". I have to be frank; I have no
idea what this means. What should I do to fix this?
--
http://mail.python.org/mailman/listinfo/python-list
Re: webbrowser module's Firefox support
MonkeeSage wrote:
> Dustan wrote:
> > >>> cont=webbrowser._browsers['firefox'][1]
>
> Why not use the api? cont=webbrowser.get('firefox')
That didn't work either.
> > ValueError: close_fds is not supported on Windows platforms
> >
> > Looking in the docs on subprocess.Popopen
> > (http://docs.python.org/lib/node529.html), it says "If close_fds is
> > true, all file descriptors except 0, 1 and 2 will be closed before the
> > child process is executed. (Unix only)". I have to be frank; I have no
> > idea what this means. What should I do to fix this?
>
> It just means that on *nix there is an option to close all open file
> handles except stdin, out and err before the browser is called. I'm
> thinking that mabye get() does an OS check to see how to call
> subprocess.Popen, and you effectively bypassed it by using the
> lower-level _browsers attribute. But I could be wrong. Try it with
> get() and see how that goes.
>
> Regards,
> Jordan
Another thing: your fix is only temporary. Is there a way to make it
work even after I close IDLE? I changed the command you gave me a bit
so it doesn't get rid of the other paths:
os.environ["PATH"]+=";C:\Program Files\Mozilla Firefox;" # can't
remember the path for firefox right now...
But either way, it ends up going right back to the previous value after
I close IDLE.
--
http://mail.python.org/mailman/listinfo/python-list
Re: webbrowser module's Firefox support
MonkeeSage wrote: > Dustan wrote: > > That didn't work either. > > Well, I'm out of ideas. It's also odd that it was being read as > webbrowser.BackgroundBrowser...whatever that is! It should have been > webbrowser.Mozilla. Thanks anyway; you have helped me tremendously. I'm sure I'll get somewhere with this... > > Another thing: your fix is only temporary. Is there a way to make it > > work even after I close IDLE? I changed the command you gave me a bit > > so it doesn't get rid of the other paths: > > > > os.environ["PATH"]+=";C:\Program Files\Mozilla Firefox;" # can't > > remember the path for firefox right now... > > > > But either way, it ends up going right back to the previous value after > > I close IDLE. > > Yeah, sorry about that, I meant to mention that changes to os.environ > only last for the life of the python process. To set / change > environment variables like PATH permanently, check out this page: > http://www.cims.nyu.edu/systems/platforms/windows/setpath.html Great! Thanks! > Regards, > Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: webbrowser module's Firefox support
> > This is a bug, and has now been fixed in SVN. As a workaround, you can > edit the webbrowser.py file and remove the close_fds and preexec_fn arguments > to Popen. > > Georg Finally! It's working. Thank you so much! -- http://mail.python.org/mailman/listinfo/python-list
Re: does anybody earn a living programming in python?
walterbyrd wrote: > > > > Well I do. So do the other dozen or so developers at my company. We're > > looking > > to hire a few more, in fact. > > > > I'm surprised. It seems I never see listings for python developers. > > I didn't mean any disrespect. I think python is a great language. It > just doesn't seem like there is much demand for professional python > developers. What about Google? A good portion of their work is in python... -- http://mail.python.org/mailman/listinfo/python-list
Strange sorting error message
I'm hiding some of the details here, because I don't want to say what I'm actually doing. I have a special-purpose class with a __cmp__ method all set up and ready to go for sorting. Then I have a special class that is based on the builtin type list (though I didn't actually inherit list; I probably should). When I create an instance with 2 or more items, and attempt to sort it, I get this strange error message: >>> myList.sort() Traceback (most recent call last): File "", line 1, in File "[listModulePath]", line 239, in sort self.listOfObjects.sort() TypeError: an integer is required The sort method's code is exactly what you see; it's a one-line method. The only thing I can think of is the __cmp__ method is returning something other than an integer, which it's not. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange sorting error message
Diez B. Roggisch wrote: > Dustan schrieb: > > I'm hiding some of the details here, because I don't want to say what > > I'm actually doing. > > > I have a special-purpose class with a __cmp__ method all set up and > > ready to go for sorting. Then I have a special class that is based on > > the builtin type list (though I didn't actually inherit list; I > > probably should). When I create an instance with 2 or more items, and > > attempt to sort it, I get this strange error message: > > > >>>> myList.sort() > > Traceback (most recent call last): > > File "", line 1, in > > File "[listModulePath]", line 239, in sort > > self.listOfObjects.sort() > > TypeError: an integer is required > > > > The sort method's code is exactly what you see; it's a one-line method. > > > > The only thing I can think of is the __cmp__ method is returning > > something other than an integer, which it's not. > > Does stuffing the objects in a standard list and sorting them work? How > does the __cmp__-method look like? Whoops, I had created the variable returnValue in __cmp__, but forgotten to return it. Now it works. That was a dumb mistake; sorry for the trouble. -- http://mail.python.org/mailman/listinfo/python-list
Re: a -very- case sensitive search
Ola K wrote: > Hi, > I am pretty new to Python and I want to make a script that will search > for the following options: > 1) words made of uppercase characters -only- (like "YES") > 2) words made of lowercase character -only- (like "yes") > 3) and words with only the first letter capitalized (like "Yes") > * and I need to do all these considering the fact that not all letters > are indeed English letters. > > I went through different documention section but couldn't find a right > condition, function or method for it. > Suggestions will be very much appriciated... > --Ola I'm not sure exactly what you mean by "considering the fact that not all letters are indeed English letters"; you could mean you don't care about the non-english characters, or you could mean you don't want any non-english characters at all (so the function should return False in that case). If the case is the former, there's a simple test for each: >>> word = 'hi' >>> word.upper() == word # evaluates to True if the word is all caps False >>> word.lower() == word # evaluates to True if the word is all lowercase True >>> word.title() == word # evaluates to True if the word is in a title format False >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: a -very- case sensitive search
Dustan wrote: > Ola K wrote: > > Hi, > > I am pretty new to Python and I want to make a script that will search > > for the following options: > > 1) words made of uppercase characters -only- (like "YES") > > 2) words made of lowercase character -only- (like "yes") > > 3) and words with only the first letter capitalized (like "Yes") > > * and I need to do all these considering the fact that not all letters > > are indeed English letters. > > > > I went through different documention section but couldn't find a right > > condition, function or method for it. > > Suggestions will be very much appriciated... > > --Ola > > I'm not sure exactly what you mean by "considering the fact that not > all letters are indeed English letters"; you could mean you don't care > about the non-english characters, or you could mean you don't want any > non-english characters at all (so the function should return False in > that case). If the case is the former, there's a simple test for each: > > >>> word = 'hi' > >>> word.upper() == word # evaluates to True if the word is all caps > False > >>> word.lower() == word # evaluates to True if the word is all lowercase > True > >>> word.title() == word # evaluates to True if the word is in a title format > False > >>> If you're using google groups, it for some reason thought my example code was 'quoted text', which it certainly isn't, seeing as it's not found anywhere prior to my message. -- http://mail.python.org/mailman/listinfo/python-list
Re: a -very- case sensitive search
Steven D'Aprano wrote:
> On Sat, 25 Nov 2006 13:39:55 -0800, Ola K wrote:
>
> > Hi,
> > I am pretty new to Python and I want to make a script that will search
> > for the following options:
> > 1) words made of uppercase characters -only- (like "YES")
> > 2) words made of lowercase character -only- (like "yes")
> > 3) and words with only the first letter capitalized (like "Yes")
> > * and I need to do all these considering the fact that not all letters
> > are indeed English letters.
> >
> > I went through different documention section but couldn't find a right
> > condition, function or method for it.
>
> At the command prompt:
>
>
> >>> dir('')
> # result edited for clarity
> [ ... 'isalnum', 'isalpha', 'isdigit', 'islower',
> 'isspace', 'istitle', 'isupper', ... ]
>
> Then do this:
>
> >>> help(''.islower)
>
> and read the text it provides. Then experiment on the command line:
>
> >>> 'abcd1234'.islower()
> True
> >>> 'aBcd1234'.islower()
> False
Forget what I said; I didn't know about the str.is* methods.
> Then come back to us if they aren't suitable, and tell us WHY they aren't
> suitable.
>
>
> --
> Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
Eduardo "EdCrypt" O. Padoan wrote: > > > > One might prefer to check for string-ness, as strings can > > duck-type somewhat like lists: > > > > my_list = ['my', 'brain', 'hurts'] > > my_string = 'Are you the brain specialist?' > > > > for test in [my_list, my_string]: > > try: > > for thing in test: > > process_list_item(thing) > > except Exception: #whatever flavor you want > > The exception should be the one that process_list_item raises when it > receives a string instead of a list. if you want to treat strings and > list in different ways, maybe it means that you are doing different > operations on then, like appendind things to the list or whatever. If > not, than you maybe want to test the types. > > > process_string(thing) # not called because > > #strings are iterable > > What if you invert your code? > > > for test in [my_string, my_list]: > try: > process_string_item(thing) > #suppose process_string_item does some string operation on a > list and gets this > # exception - because if not, I see no meanning in distinguishing then In case you had trouble reading the comments because it was too wide: "suppose process_string_item does some string operation on a list and gets this exception - because if not, I see no meanning in distinguishing then" Has it occurred to you that perhaps the OP wants to do very different operations depending on whether or not the item is of type str or list? And since a list can in many cases act very similarly to a string, the best way to distinguish would be a type check, especially since the OP knows what tools are being used to receive the output. > except ValueError: > for thing in test: > process_list_item(thing) > > But maybe you have a reason to do things to a string that could be > done to a list without raising an exception, but you dont want to do > this to *that* list. My sugestion was to think if there is another > way, and maybe you are right. > > > -- > EduardoOPadoan (eopadoan->altavix::com) > Bookmarks: http://del.icio.us/edcrypt > Blog: http://edcrypt.blogspot.com > Jabber: edcrypt at jabber dot org > ICQ: 161480283 > GTalk: eduardo dot padoan at gmail dot com > MSN: eopadoan at altavix dot com -- http://mail.python.org/mailman/listinfo/python-list
Re: The del statement
Marco Aschwanden wrote: > > do you find the x[i] syntax for calling the getitem/setitem methods a > > bit awkward too? what about HTTP's use of "GET" and "POST" for most > > about everything ? ;-) > > No. I like the x[i] syntax. I use it in every second row of my code and > getting an item like: > > x.getitem(i) That's spelled "x.__getitem__(i)". Still prefer the method call? > would be a viable (in this case clumsy) way but here I find the introduced > syntax justified. > del on the other hand is used sparingly througout my code. If no del > keyword would exist, it wouldn't disturb me. "del x[i]" calls "x.__delitem__(i)". I can't say specifically what list.__delitem__ does, but looking it up in IDLE (l is an instance of list): >>> l.remove >>> l.__getitem__ >>> l.__delitem__ It seems that list.__delitem__ is a different type than the rest, called method-wrapper. I can only guess from this point; someone else is bound to know about this. > Marco I can see some builtin functions leaving, but the del keyword isn't exactly unimportant. Looking at the documentation on the del statement: http://docs.python.org/ref/del.html There is no note saying that del is deprecated. That really doesn't mean anything; it could always become deprecated in the future, but it doesn't seem likely. -- http://mail.python.org/mailman/listinfo/python-list
Re: reloading modules
[EMAIL PROTECTED] wrote: > I'm using python.exe to execute my modules. I have a music.py module > which contains my classes and a main.py module which uses these > classes. In python.exe, I call "import main" to execute my program. The > problem is that I have to close python and reopen it everytime i change > music.py or main.py. What should I be doing. > > Thanks, > > Aine. >>> import main ### Execution Occurs ### >>> # You go off to edit your module >>> reload(main) ### Execution Occurs ### -- http://mail.python.org/mailman/listinfo/python-list
Re: reloading modules
Dustan wrote: > [EMAIL PROTECTED] wrote: > > I'm using python.exe to execute my modules. I have a music.py module > > which contains my classes and a main.py module which uses these > > classes. In python.exe, I call "import main" to execute my program. The > > problem is that I have to close python and reopen it everytime i change > > music.py or main.py. What should I be doing. > > > > Thanks, > > > > Aine. > > >>> import main > ### Execution Occurs ### > >>> # You go off to edit your module > >>> reload(main) > ### Execution Occurs ### I was obviously assuming that your module does something just by importing, which may or may not be the case. Either way, whenever a module may have been edited during a program's lifetime, it can be reloaded using the reload function. -- http://mail.python.org/mailman/listinfo/python-list
Re: Emulate @classmethod using decorator and descriptor
WaterWalk wrote: > Hello, I was recently learning python decorator and descriptor and > emulated a @classmethod decorator: > class EmuClassMethod(object): > def __init__(self, f=None): > self.f = f > def __get__(self, obj, klass=None): > if klass is None: >klass = type(obj) > def wrapped(*args): >return self.f(klass, *args) > return wrapped > > class Test(object): > @EmuClassMethod > def t(cls): > print "I'm %s" % cls.__name__ > > It worked, and seems that a function decorator works as follows: > # decf is a decorator > @decf > def func(): > print 'func' > > will be "converted" to: > > def func(): > print 'func' > func = decf(func) > > Is this really the case? Or correct me if i'm wrong. Thanks in advance. Yes, the two are equivalent. The documentation is found here: http://docs.python.org/ref/function.html But I personally found the explanation for decorators a bit confusing. -- http://mail.python.org/mailman/listinfo/python-list
Re: slices - handy summary
meridian wrote: > If, like me, you're always forgetting which way around your list/seq > slices need to go then worry no more. Just put my handy "slice > lookupper" (TM) ) on a (large!) PostIt beside your screen and, Hey > Presto! no more tediously typing a 1-9 seq into your interpreter and > then getting a slice just to check what you get.. (Yes you. You know > you do that !) ...Cheers Steve Actually, I don't. I just remember that, for a natural (positive nonzero) number y: x[:y] is the first y elements x[-y:] is the last y elements As shown here: >>> x = range(5) >>> x [0, 1, 2, 3, 4] >>> x[:2] [0, 1] >>> x[-2:] [3, 4] >>> And I just work it out from there. Just my method for remembering slices, that happens to work pretty well for me. > x = '0123456789' > > x[-10: ] 0123456789 x[ 0: ] > x[ -9: ] 123456789 x[ 1: ] > x[ -8: ] 23456789 x[ 2: ] > x[ -7: ] 3456789x[ 3: ] > x[ -6: ] 456789 x[ 4: ] > x[ -5: ] 56789 x[ 5: ] > x[ -4: ] 6789 x[ 6: ] > x[ -3: ] 789x[ 7: ] > x[ -2: ] 89 x[ 8: ] > x[ -1: ] 9 x[ 9: ] > > x[ :-9 ] 0 x[ :1 ] > x[ :-8 ] 01 x[ :2 ] > x[ :-7 ] 012x[ :3 ] > x[ :-6 ] 0123 x[ :4 ] > x[ :-5 ] 01234 x[ :5 ] > x[ :-4 ] 012345 x[ :6 ] > x[ :-3 ] 0123456x[ :7 ] > x[ :-2 ] 01234567 x[ :8 ] > x[ :-1 ] 012345678 x[ :9 ] > 0123456789 x[ :10 ] -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Creating Exception
johnny wrote: > Thank you Dennis, > So when line 2, gets executed, its exception goes to do_some1_error. > And when line 3, gets executed, its exception goes to do_some2_error > and so on. > > line 1: try > line 2:do_some1 > line 3:do_some2 > line 4:do_some3 > line 5: except do_some1_error: > line 6:whatever1 > line 7: except do_some2_error: > line 8:whatever2 > line 9: except do_some3_error: > line 10:whatever3 > > Documentation is not written for newbs, it's written by guys with 6yrs > of experience FOR guys with 6yrs of experience. You might want to get a book on python, rather than depend on the documentation, which is, as you say, written for more experienced programmers. http://wiki.python.org/moin/IntroductoryBooks I started with a book, and reading the tutorial now, am quite glad I did. One thing that did bug me, at least briefly, is sometimes beginner books don't explain what a line of code is actually doing - not necessarily how it works, but as much information as is necessary to actually be able to use the code shown. > Dennis Lee Bieber wrote: > > On 11 Dec 2006 16:02:02 -0800, "johnny" <[EMAIL PROTECTED]> declaimed > > the following in gmane.comp.python.general: > > > > > I want to print individual exception for database connection, sql > > > execution, database closing, closing the cursor. Can I do it with one > > > try..catch or I need a nested try...catch? > > > > Python does not have a "catch" instruction. > > > > You could do: > > > > try: > > make connection #though that should, in my mind, be done > > #as part of the > > initialization of the thread > > #and not as part of any > > processing loop > > make cursor > > execute sql > > fetch results if any > > close cursor > > commit transaction > > close connection#which I'd make part of the termination > > #of the thread > > except Exception1, msg: > > do something > > except Exception2, msg: > > do something2 > > ... > > > > IF each step raises a different exception type -- if all the database > > returns is "DatabaseError", then there is nothing to separate them by. > > Also note that if an exception happens in the "execute sql" stage, your > > handler may need to do a rollback, and the closes. > > > > -- > > WulfraedDennis Lee Bieber KD6MOG > > [EMAIL PROTECTED] [EMAIL PROTECTED] > > HTTP://wlfraed.home.netcom.com/ > > (Bestiaria Support Staff: [EMAIL PROTECTED]) > > HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Creating Exception
Dustan wrote: > johnny wrote: > > Documentation is not written for newbs, it's written by guys with 6yrs > > of experience FOR guys with 6yrs of experience. > > You might want to get a book on python, rather than depend on the > documentation, which is, as you say, written for more experienced > programmers. > > http://wiki.python.org/moin/IntroductoryBooks > > I started with a book, and reading the tutorial now, am quite glad I > did. One thing that did bug me, at least briefly, is sometimes beginner > books don't explain what a line of code is actually doing - not > necessarily how it works, but as much information as is necessary to > actually be able to use the code shown. I didn't complete my thought. If you run into a situation like this, then you might want to look to the python documentation on the web for help; think of the web documentation as a reference manual rather than a tutorial, even though it does provide a tutorial. -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Creating Exception
Dennis Lee Bieber wrote: > On 13 Dec 2006 03:52:49 -0800, "Dustan" <[EMAIL PROTECTED]> > declaimed the following in gmane.comp.python.general: > > > > > I didn't complete my thought. If you run into a situation like this, > > then you might want to look to the python documentation on the web for > > help; think of the web documentation as a reference manual rather than > > a tutorial, even though it does provide a tutorial. > > I believe it was stated that the installation was using the > ActiveState build. The documentation is supplied in Windows CHM format, > which is likely much faster to search/read locally than loading a chain > of web pages. I couldn't think of a better word to describe the 'official' documentation. > Including, last time I checked, an electronic copy of "Dive into > Python" -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
vertigo wrote: > Hello > > I receive such error: > File "p4.py", line 24, in PrintWordCountFloat > print "%s %f" % (word,words[word]) > TypeError: list indices must be integers > > i call PrintWordCountFloat with hash table, keys are words(string) and > values float. > This part of the code: > > def PrintWordCountFloat(words): > number = 0 > for word in words: > print "%s %f" % (word,words[word]) #line 24 > number = number + 1 > print "Total words: %d" %(number) > > My function displays whole table correctly, and after that i receive > mentioned error. > Why ? Where is the problem ? Perhaps you meant something more along the lines of this: >>> def PrintWordCountFloat(words): number = 0 for index, word in enumerate(words): print "%s %f" % (index, word) number = number + 1 print "Total words: %d" %(number) >>> PrintWordCountFloat(range(10)) 0 0.00 1 1.00 2 2.00 3 3.00 4 4.00 5 5.00 6 6.00 7 7.00 8 8.00 9 9.00 Total words: 10 Or similar; I can't read your mind. Just know that enumerate(iterable) yields (index, value) for each item in iterable. > Thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
Kleine Aap wrote: > Asper Faner wrote: > > > I seem to always have hard time understaing how this regular expression > > works, especially how on earth do people bring it up as part of > > computer programming language. Natural language processing seems not > > enough to explain by the way. Why no eliminate it ? > > I.M.H.O. anyone that is not capable to grasp the concept of regular > expressions should not attempt to write computer programs at all! My > suggestion to you would be to find a job that involves working with your > hands... Your humble opinion doesn't get much ruder... Perhaps you meant "anyone that is not capable to grasp the concept of regular expressions after some experience with programming should not attempt to write computer programs at all!" Then at least newbies would have a leg to stand on. Otherwise, you're practically cutting off all entrances into the world of programming! The concept of regular expressions isn't exactly the simplest one out there. Just because you understood it immediately (which I'm guessing you did, considering your harsh response), doesn't mean others find the concept that simple. -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
[EMAIL PROTECTED] wrote: > Rad [Visual C# MVP] wrote: > > On Sun, 24 Dec 2006 16:36:31 +0100, Stef Mientki wrote: > > > > > Dustan wrote: > > >> Kleine Aap wrote: > > >>> Asper Faner wrote: > > >>> > > >>>> I seem to always have hard time understaing how this regular expression > > >>>> works, especially how on earth do people bring it up as part of > > >>>> computer programming language. Natural language processing seems not > > >>>> enough to explain by the way. Why no eliminate it ? > > Hi folks, fairly new to the list(Python is my first programming > language, so I'm fairly new to the world of programming too)but this is > a question I've been wondering about since I started learning about the > re module. Are regular expressions what makes mark up languages > interpretable by webbrowsers? I don't actually know the answer, but my educated guess: Regular expressions are just the simplest way to parse any text, but there are other ways. Webbrowsers most likely depend on regular expressions just because it's a relatively quick and easy way to interpret the language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does Python never add itself to the Windows path?
WaterWalk wrote: > Ben Sizer wrote: > > I've installed several different versions of Python across several > > different versions of MS Windows, and not a single time was the Python > > directory or the Scripts subdirectory added to the PATH environment > > variable. Every time, I've had to go through and add this by hand, to > > have something resembling a usable Python installation. No such > > problems on Linux, whether it be Mandrake/Mandriva, Fedora Core, or > > Kubuntu. So why is the Windows install half-crippled by default? I just > > rediscovered this today when trying to run one of the Turbogears > > scripts, but this has puzzled me for years now. > > > > Well, after Python is installed on a Windows platform, files with > extention ".py" or ".pyw" are automatically associated with python or > pythonw. If a python script is double-clicked or input something like > "sth.py" in the "cmd" box, the python interpreter is automatically > called. I don't see any proplem or inconvenience with this. In the command line, entering "python" does not run the python interpreter (unless you modify the settings yourself). -- http://mail.python.org/mailman/listinfo/python-list
Re: strange for loop construct
Mark Elston wrote: > * Gabriel Genellina wrote (on 1/5/2007 12:49 PM): > > At Friday 5/1/2007 17:39, [EMAIL PROTECTED] wrote: > > > >> wordfreq = [wordlist.count(p) for p in wordlist] > >> > >> I would expect > >> > >> for p in wordlist: > >> wordfreq.append(wordlist.count(p)) > >> > >> > >> I didn't know you could have an expression in the same line. > > > > That's known as a "list comprehension" and is roughly equivalent to your > > code. Section 5 of the tutorial covers them. > > http://docs.python.org/tut/node7.html > > > > > > If you have a Python installation you should be able to find the > "Whats New" section of the docs. List comprehensions are described > pretty well in the "What's new in Python 2.0?" section. This gives > some simple examples as well as the rationale behind them. Shouldn't that same page be found on the python website? http://www.python.org/doc/2.0/ Any clue as to why it isn't? > Mark -- http://mail.python.org/mailman/listinfo/python-list
Numeric Entry in Tkinter
Earlier I asked about limitting what a user can enter in an Entry. I got a few greatly appreciated replies, but I was hoping it would be possible to take a more direct approach, that is, is there a method I can override, when creating a class that inherits the Entry methods, that is called whenever the user enters a key? I'm thinking something like this in the override version: def method(self, key): if key in "1234567890": Entry.method(self, key) else: pass Is this possible? I suppose key would actually be accessed using an associated get() method or something of the sort, but you get the idea. Is there such a method? -- http://mail.python.org/mailman/listinfo/python-list
Get System Date?
Is it possible to get the system date on a Windows XP machine? Most Convenient would to retrieve , MM, and DD as seperate variables. When I say system date, I'm thinking of the small clock in the lower-right hand corner, which has date as well as time, but if there's another clock that Python supports, it works for me as long as it's somewhat accurate. -- http://mail.python.org/mailman/listinfo/python-list
Re: Get System Date?
Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Pop Quiz
On Jun 1, 9:33 pm, [EMAIL PROTECTED] wrote: > 1. Do you like Python? yes > 2. Do you think Python is good? yes > 3. Do you think Python is real good? yes > 4. What is your favorite version of Python? The most recent one. > 5. Because of Python, do you think it will be easier to take over the > world? I don't know; I've never considered taking over the world. > If so, when? If not, when? > > 7. How many Z80 assembly language programmers does it take to equal > one Python guru? I don't know about Z80, but the word 'assembly' makes me think: .4 > Essay: "C++ is better than C", agree or disagree? (four word maximum) I can not say. > Bonus: A rabbi walks into a bar while nursing a baby goat. He is > closely followed by a priest, and a Perl hacker. Explain. I'm glad this is just bonus. What do I win? -- http://mail.python.org/mailman/listinfo/python-list
Re: function in a function accessing vars
On Jun 6, 6:40 am, "Jorgen Bodde" <[EMAIL PROTECTED]> wrote: > Hi Diez, > > Thanks, I thought it worked similar to C++ where a higher compound > could access a lower section. It can 'access a lower section'; what it can't do is *change* that 'lower section'; in your example case with an int, this matters because ints are immutable. Lists, on the other hand, are mutable. You can *access* the methods of the list that mutate it. You're always working with the same list, but it has different contents when you mutate it. > But as it is not straight forward, I > think it is better to embed the functionality inside a class, and make > it a member variable .. now why didn't I think of that ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Determinant of Large Matrix
On Jun 6, 6:47 am, Tommy Nordgren <[EMAIL PROTECTED]> wrote: > On 6 jun 2007, at 13.10, James Stroud wrote: > > > > > Hello All, > > > I'm using numpy to calculate determinants of matrices that look like > > this (13x13): > > > [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] > > [ 1. 0. 1. 4. 1. 9. 4. 4. 1. 1. 4. 9. 4. 9.] > > [ 1. 1. 0. 1. 4. 4. 9. 9. 4. 4. 1. 4. 1. 4.] > > [ 1. 4. 1. 0. 9. 1. 4. 4. 9. 1. 4. 1. 4. 1.] > > [ 1. 1. 4. 9. 0. 4. 4. 4. 1. 4. 1. 9. 4. 9.] > > [ 1. 9. 4. 1. 4. 0. 4. 4. 9. 4. 1. 1. 4. 1.] > > [ 1. 4. 9. 4. 4. 4. 0. 1. 1. 1. 9. 1. 9. 4.] > > [ 1. 4. 9. 4. 4. 4. 1. 0. 4. 1. 9. 4. 4. 1.] > > [ 1. 1. 4. 9. 1. 9. 1. 4. 0. 4. 4. 4. 4. 9.] > > [ 1. 1. 4. 1. 4. 4. 1. 1. 4. 0. 9. 4. 9. 4.] > > [ 1. 4. 1. 4. 1. 1. 9. 9. 4. 9. 0. 4. 1. 4.] > > [ 1. 9. 4. 1. 9. 1. 1. 4. 4. 4. 4. 0. 4. 1.] > > [ 1. 4. 1. 4. 4. 4. 9. 4. 4. 9. 1. 4. 0. 1.] > > [ 1. 9. 4. 1. 9. 1. 4. 1. 9. 4. 4. 1. 1. 0.]] > > > For this matrix, I'm getting this with numpy: > > > 2774532095.971 > > > But I have a feeling I'm exceeding the capacity of floats here. Does > > anyone have an idea for how to treat this? Is it absurd to think I > > could > > get a determinant of this matrix? Is there a python package that could > > help me? > > > Many thanks for any answers. > > > James > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Are you sure NumPy return float results. As far as I know, it > returns doubles I don't know about NumPy, but in general, a python float is a double: http://docs.python.org/lib/typesnumeric.html "Floating point numbers are implemented using double in C. All bets on their precision are off unless you happen to know the machine you are working with." > (about 16 digits) > -- > "Home is not where you are born, but where your heart finds peace" - > Tommy Nordgren, "The dying old crone" > [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: get a list from a string
On Jun 7, 6:06 am, simon kagwe <[EMAIL PROTECTED]> wrote:
> > exec("distances = [[1,1,1,1],[2,2,2,2]]")
To be clear, exec is *not* a function; it's a statement. That means it
can't be used in lambda functions, for example.
> Wow! So simple!
but dodgy, as it'll execute any python code.
> Thanks a lot. :-)
--
http://mail.python.org/mailman/listinfo/python-list
Re: running a random function
On Jun 7, 10:56 am, David Bear <[EMAIL PROTECTED]> wrote: > I would like to write some code that would randomly select a function from a > list of functions and call it. I was looking in the globals names space and > randomly selecting items that were of type function.. Careful!!! You don't want to destroy your computer by accident. > but I didn't see a > way of actually running the function. What do you mean? foo is a function; here's how you run it: foo() > Any pointers? Given a list of functions, it would simply be, given the list of functions bar (untested): import random random.choice(bar)() -- http://mail.python.org/mailman/listinfo/python-list
Re: running a random function
On Jun 7, 1:30 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote: > On 2007-06-07, Stebanoid <[EMAIL PROTECTED]> wrote: > > > if you have a list of functions you can try this: > > > import random > > import math > > m[int(math.floor(len(m)*random.random()))]() # seems like Lisp > > Or rather m[random.randint(0, len(m))]() Or rather random.choice(m)() # seems like Python > -- > Neil Cerutti > Caution: Cape does not enable user to fly. --Kenner's Batman costume -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
On Jun 13, 5:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, Diez B. Roggisch wrote: > > > No need to create the intermediate list, a generator expression works just > > fine: > > > a = tuple(i for i in range(10)) > > But `range()` creates the intermediate list anyway. ;-) I imagine that's special case. -- http://mail.python.org/mailman/listinfo/python-list
