Re: [Tutor] Tix and Table printing
I'm not yet used to search in the cookbook... and I though such basic widget would have been implemented directly in Tk or Tix... A bit of historic perspective. John Ousterhout invented TCl/Tk to provide a control language for his electrical engineering projects. Thus its focus is on GUIs to control hardware rather than display data, so a table widget wasn't an obvious requirement. In fact table widgets didn't become common in GUI toolkits till the mid '90's when Visual Basic introduced one, then Delphi, then everyone started adding them when it became obvious how useful they were. But the first version of MFC (the Windows native GUI) and also the Smalltalk GUI (one of the first ever) had no table widget, programmers had to craft their own! Tk was written in the 80's so given its origins was not likely to have a table. Of course it would be nice if they added one now!!! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] reinitializing namespace
Dear Kent, Consider I'm working with an interactive session during which I have already run some scripts. Those scripts have produced several variables, say, e.g., a and b. Now I execute myscript which also creates variables named a and b, but with a possibly different type or content. To be sure that the variables I find in my workspace after the execution of myscript were created by this script and not by another one, I want to reset the workspace. Otherwise, how can I make a difference between variables having the same name but created by two different scripts? Maybe this question is too much related to my Matlab experience and not relevant into Python's philosophy. Please tell me what I should do. Dimitri -Message d'origine- De : [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] De la part de Kent Johnson Envoyé : vendredi 14 janvier 2005 12:03 Cc : tutor@python.org Objet : Re: [Tutor] reinitializing namespace I think you may be looking for something that is not needed in Python or that you can easily do another way. If you are running a script from the command line, e.g. python myscript.py then myscript.py will have a completely fresh runtime environment every time you call it. If you are running the script by importing in another module, then you can use reload() to reload the imported script. That will reinitialize the namespace of the module, which for your purposes *is* the global namespace of the module. Please give us more details about how you will run the script and what kind of problem you anticipate. Kent Dimitri D'Or wrote: Hello Michael, Thank you for your answer. Actually, my question is not specific to interactive sessions. I've written a script that loads some modules, create variables and show figures. What I would like to find, is a command for clearing all the created variables and close all figures before beginning the execution of the script. This command will be placed at the beginning of the script and automatically reinitialize the namespace. The utility of this command is to guarantee that all the variables that are available in the namespace after the execution of the script were created by it and are not remainders from older commands or scripts. Do you think it is possible to do such a thing? I'm coming from the Matlab world and I want to find equivalents for the clear and close matlab commands. Thank you for your help, Dimitri -Message d'origine- De : Michael Janssen [mailto:[EMAIL PROTECTED] Envoyé : jeudi 13 janvier 2005 19:29 À : Dimitri D'Or Cc : tutor@python.org Objet : Re: [Tutor] reinitializing namespace On Thu, 13 Jan 2005 13:20:11 +0100, Dimitri D'Or [EMAIL PROTECTED] wrote: For some purpose, I would like to reinitialize the main namespace, i.e. I want to delete all the variables I have created through the use of functions or keyboard entries. Hello Dimiti, sound like you're talking about an interactive session. Otherwise (within a script) it would be a really bad idea to try this (better put your stuff into functions, that don't create global variables). Even in an interactive session it sounds like a not that brilliant idea, especially since I can't think of a way other than using exec del %s % key for appropriate keys from globals(). Finding appropiate keys is one tricky thing. Why not end your ugly python session and start a new one? You can define all your imports in the python startfile (on Linux, consult python manpage. On Windows, I don't know). You can also define useful functions or variables in your python startfile. This way, you're really shure that all ugly variables are away without del'iting anything important. regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] l10n and Windows
Hi, After searching a while for a solution on the web and the archive of this newgroups, I haven't found any answer to my questions... So here are they... Here is a command line session of Python on a Windows XP computer : Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import locale locale.getdefaultlocale() ('fr_CA', 'cp1252') locale.setlocale(locale.LC_ALL, '') 'French_Canada.1252' locale.setlocale(locale.LC_ALL, 'en_CA') Traceback (most recent call last): File stdin, line 1, in ? File C:\Python24\Lib\locale.py, line 379, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting locale.setlocale(locale.LC_ALL, 'English_Canada') 'English_Canada.1252' locale.getlocale() ['English_Canada', '1252'] The name of the default locale conform to RFC-1766 (http://www.faqs.org/rfcs/rfc1766.html) when returned by locale.getdefaultlocale whereas setting the locale as 'en_CA' isn't supported (on Windows). Afterwards, locale.getlocale() isn't returning a standard RFC-1766 locale at all... Is this a feature or a bug ? Where has portability gone ? Moreover on the documentation on locale.getlocale(), it is written: Except for the code 'C', the language code corresponds to RFC 1766 Thanks for you help. Stéphane ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] file-like object
I have created a file-like object out of a triple quoted string. I was wondering if there is a better way to implement readline than what I have below? It just doesn't seem like a very good way to do this. class _macroString(object): def __init__(self,s): self.macro=s self.list=self.macro.split(\n) for n,v in enumerate(self.list): self.list[n]=v+'\n' def readline(self,n=[-1]): n[0]+=1 return self.list[n[0]] def __str__(self): return str(self.list) def __len__(self): return len(self.list) __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file-like object
Best: use the StringIO or cStringIO module instead, this is exactly what it is for. If you really need len() you could maybe subclass StringIO to do what you want. Next best: Use an iterator. Something like this (Warning! not tested!): class _macroString(object): def __init__(self,s): self.macro=s self.list=[ line+'\n' for line in self.macro.split(\n) ] self._iter = iter(self.list) def readline(self): try: return self._iter.next() except StopIteration: return '' def __str__(self): return str(self.list) def __len__(self): return len(self.list) Note that your implementation of readline will raise IndexError when there are no more lines which is not correct behaviour. Kent Chad Crabtree wrote: I have created a file-like object out of a triple quoted string. I was wondering if there is a better way to implement readline than what I have below? It just doesn't seem like a very good way to do this. class _macroString(object): def __init__(self,s): self.macro=s self.list=self.macro.split(\n) for n,v in enumerate(self.list): self.list[n]=v+'\n' def readline(self,n=[-1]): n[0]+=1 return self.list[n[0]] def __str__(self): return str(self.list) def __len__(self): return len(self.list) __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Referer file from import
You could use trackback.extract_stack() to get the current stack trace. If you inspect this from within the imported module you could probably figure out who is importing you. Do you really want the module where the import was done (the place where the import statement is)? Or are you trying to find the file containing the imported module? Kent Isr Gish wrote: Chad Crabtree wrote: Is there a way to know what the path of the file is that imported a module? I've tried __file__ and playing with globals() but I can't seem to crack this. There most be a way because the Tracebacks give us this info. You want to take a look at the 'inspect' module. I belive looking at the source of the traceback module may help alot. All the best, Isr ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Referer file from import
Ok I will investigate this. Thank you that is probably what I needed. I am trying to make a macro expander for python based on BOO's facility for this. I thought it was neat. In addition I think it would be helpful to simulate adding keywords so that all these bloggers talking about proposed syntax could actually try it. But mostly I want to implement the with keyword with g: append(1) append(2) append('woah') Kent Johnson wrote: You could use trackback.extract_stack() to get the current stack trace. If you inspect this from within the imported module you could probably figure out who is importing you. Do you really want the module where the import was done (the place where the import statement is)? Or are you trying to find the file containing the imported module? Kent Isr Gish wrote: Chad Crabtree wrote: Is there a way to know what the path of the file is that imported amodule? I've tried __file__ and playing with globals() but I can't seemto crack this. __ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file-like object
Thank you KentBot. That was what I wanted. Kent Johnson wrote: Best: use the StringIO or cStringIO module instead, this is exactly what it is for. If you really need len() you could maybe subclass StringIO to do what you want. Next best: Use an iterator. Something like this (Warning! not tested!): class _macroString(object): def __init__(self,s): self.macro=s self.list=[ line+'\n' for line in self.macro.split(\n) ] self._iter = iter(self.list) def readline(self): try: return self._iter.next() except StopIteration: return '' def __str__(self): return str(self.list) def __len__(self): return len(self.list) Note that your implementation of readline will raise IndexError when there are no more lines which is not correct behaviour. Kent __ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file-like object
class _macroString(object): def __init__(self,s): self.macro=s self.list=self.macro.split(\n) for n,v in enumerate(self.list): self.list[n]=v+'\n' def readline(self,n=[-1]): n[0]+=1 return self.list[n[0]] Why not just create a current pointer as a clas attribute? Increment or reset as required. after all maintaining object state is what classes and objects are for! HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file-like object
On Fri, 14 Jan 2005, Chad Crabtree wrote: class _macroString(object): def __init__(self,s): self.macro=s self.list=self.macro.split(\n) for n,v in enumerate(self.list): self.list[n]=v+'\n' Is this for loop a safe technique, where the list you're enumerating over in the for statement is the same as the one being updated in the loop body? I always avoid things like that. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tix and Table printing
On Fri, 14 Jan 2005 08:47:49 - Alan Gauld [EMAIL PROTECTED] wrote: Tk was written in the 80's so given its origins was not likely to have a table. Of course it would be nice if they added one now!!! It looks like they are already working on it: http://wiki.tcl.tk/12753 Regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file-like object
for n,v in enumerate(self.list): self.list[n]=v+'\n' Is this for loop a safe technique, where the list you're enumerating over in the for statement is the same as the one being updated in the loop body? I always avoid things like that. Its not changing the list, its changing the list contents. If it were adding or re,moving items from the list that would be dodgy, but modifying a existing element doesn't really change the list itself in any significant way. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] style question: when to hide variable, modules
A few thoughts: - you might want to make a configuration object that you can pass around, this is probably better than passing around an instance of the main Burn class. - typical Python style is *not* to define setter and getter functions. If you need to mediate attribute access you can do it later using properties. - you might want to consolidate your classes into a small number of modules. This is the style of much of the Python standard library. Look at optparse.py for an example (picked more-or-less at random). - if one class has a helper class or function that isn't used anywhere else, put the helper into the same module as the client and name the helper starting with _. - I tend to worry more about naming with _ in a module that is likely to be reused. For a module that will probably be only be used once, I don't use _ at all. In a module that has a public API I try to use _ to distinguish the implementation details from the public stuff. HTH Kent Paul Tremblay wrote: During the recent discussion on jython, a poster brought up the good point that one should hide variables and modules to indicate that they are not for public use: self.__for_internal_purposes = 5 __internal_stuff.py This module only makes sense for use with the parent module. So one could write several modules using these guidelines. One could then issue the command from a shell pydoc internal_stuff, and sure enough, one gets a nice listing of all the methods with the __methods listed first, signalling to someone who hasn't written the program (or to the author who returns to it a few years later), that one shouldn't look at these methods when looking what is useful from the script. My question is, how far should one take these guidlines? I am working on an OO script with several modules that backs up a hardrive. There will be about 10 modules, but really only *one* of them, called backup, would be used as a pubilc interface. Should I name the rest of them things like __handle_archive.py, __file_system.py, and so on? That seems odd, since I have never seen this done before. However, it does have an elegance of clearly telling someone how to hook into the modules. Also, maybe more importantly, I want to know how to handle attributes that need to be shared. Imagine that there are around 20 attributes, such as the level the program runs at, and the number of the disk being copied that need to be shared with different modules. Right now, my setup looks like this: # this module is called backup.py class Backup: __init__(self, verbose, level ): self.__make_objects() self.verbose = verbose self.level = level def __make_objects(self): self.burn_obj = paxbac.burn.Burn(self) self.archive_obj = paxbac.archive.Archive(self) def get_disk(self): return self.__disk def set_disk(self, the_num): self.__disk = the_num def backup(self): archive_obj.archive() burn_obj.burn() * #this is aother module called burn.py class Burn: def __init__(self, main): self.__main = main def burn(self): cd_num = self.main.get_disk() if self__main.level 3: sys.stdout.write('Burning disk %s\n' %cd_num) The main module backukp provides a number of public methods that are really not public. For examle, no one is going to want to use this module to find out what disk the method is on. If I wanted to be very strict with public and private variables and methods, I would have to: 1. change burn.py to __burn.py 2. create a module called __attributes.py, create an object in burn.py called self.__attributes_obj, and pass this object to each method. These two steps seem to take things a bit far. On the other hand, one could look at the set of modules and immediately know how to use them. Thanks Paul ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi. Is there another mailing list like this one?
I'm am bored and people are not asking enough questions/answering them to keep my mind busy. Is there any other mailing list that I can subscribe to like this one that lets anyone ask and answer questions? I assume you'vve checked the Python newsgroup? It should be busy enough for anyone! Of course the subject area is much more diverse... but you can join a mailing list variant I believe? And of course there are all the sig groups and the specialist mailing lists. Try looking through the other areas on the Community page of the web site... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help
This is my first attempt at programing and my first program sort of did work hear is the program and if any one can tell me what i did wrong or forgot i would appreciate it a = input(Type in the Grose: ) b = input(type in the Miles: ) print a * 0.74 / b is a*0.74/b as you can see it should be realy easy program once it works -- ___ Find what you are looking for with the Lycos Yellow Pages http://r.lycos.com/r/yp_emailfooter/http://yellowpages.lycos.com/default.asp?SRC=lycos10 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Matrix
Brian van den Broek wrote: 2) To get around that, and be more efficient with matricies with many empty cells: . my_matrix_as_dict = {(1,1):4, (1,2):6, (1,3):8, (2,1):56, (2,3):12, (3,1):3, (3,2):3} . my_matrix_as_dict[(3,1)] 3 . my_matrix_as_dict[(2,1)] 56 So, you just can use the tuple co-ordinates you've defined in order to access cells. Note also that the list way you'd have to represent empty cells with a standard null value -- None is the usual choice. But this way, you just don't define some tuples as keys, as I didn't define (2,2) as a key. Thus: . my_matrix_as_dict[(2,2)] Traceback (most recent call last): File pyshell#19, line 1, in -toplevel- my_matrix_as_dict[(2,2)] KeyError: (2, 2) You can make that more graceful with a try/except block: . try: my_matrix_as_dict[(2,2)] except KeyError: print That cell is empty That cell is empty . if you want None to be returned for an empty cell, you can just do: my_matrix_as_dict.get((2,2), None) so that the None object will de returned for all inexistant cells... Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file-like object
On Fri, 14 Jan 2005, Terry Carroll wrote: Is this for loop a safe technique, where the list you're enumerating over in the for statement is the same as the one being updated in the loop body? Rather than cluttering the list by making three replies, I'd just like to thank Danny, Alan and Jeff each for their answers to this. Clears it right up for me. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
On Jan 10, 2005, at 14:31, john stanley wrote: This is my first attempt at programing and my first program sort of did work hear is the program and if any one can tell me what i did wrong or forgot i would appreciate it a = input(Type in the Grose: ) b = input(type in the Miles: ) print a * 0.74 / b is a*0.74/b as you can see it should be realy easy program once it works The first thing to do is to look at the error that was caused, and what caused it. Python is good at it, as it shows you the exact line, and even the exact character where the error happened. Now, this example is trivial, but in the future, when you have such a problem, please include the traceback in your message, thanks. Anyway, the error happens in the last line, just before the last expression (a*0.74/b). Which is logical, because that expression is in no way linked to the string that's before it. I suppose you want to display the result of the expression right after the string, don't you? Then you might want to use the string concatenation operator: + It should be easy to correct, now... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Faster procedure to filter two lists . Please help
Hi Danny: Thank you for your suggestion. I tried creating a dictionary of 'what' list and searched keys with has_key method and it is pretty fast. Thanks again. following is the piece of code. K cors = [] intr = [] for i in range(len(what)): ele = split(what[i],'\t') cors.append(ele[0]) intr.append(ele[1]) what_dict = dict(zip(cors,intr)) for i in range(len(my_report)): cols = split(my_report[i],'\t') cor = cols[0] if what_dict.has_key(cor): intr = what_dict[cor] my_final_report.append(cols[0]+'\t'+intr+'\t'+cols[1]+'\t'+cols[2]) --- Danny Yoo [EMAIL PROTECTED] wrote: On Fri, 14 Jan 2005, kumar s wrote: for i in range(len(what)): ele = split(what[i],'\t') cor1 = ele[0] for k in range(len(my_report)): cols = split(my_report[k],'\t') cor = cols[0] if cor1 == cor: print cor+'\t'+ele[1]+'\t'+cols[1]+'\t'+cols[2] Hi Kumar, Ok, this calls for the use of an associative map or dictionary. The main time sink is the loop here: for k in range(len(my_report)): cols = split(my_report[k],'\t') cor = cols[0] if cor1 == cor: print cor+'\t'+ele[1]+'\t'+cols[1]+'\t'+cols[2] Conceptually, my_report can be considered a list of key/value pairs. For each element in 'my_report', the key is the first column (cols[0]), and the value is the rest of the columns (cols[1:]). The loop above can, in a pessimistic world, require a search across the whole of 'my_report'. This can take time that is proportional to the length of 'my_report'. You mentioned earlier that each list might be of length 249502, so we're looking into a process whose overall cost is gigantic. [Notes on calculating runtime cost: when the structure of the code looks like: for element1 in list1: for element2 in list2: some_operation_that_costs_K_time() then the overall cost of running this loop will be K * len(list1) * len(list2) ] We can do much better than this if we use a dictionary data structure. A dictionary can reduce the time it takes to do a lookup search down from a linear-time operation to an atomic-time one. Do you know about dictionaries yet? You can take a look at: http://www.ibiblio.org/obp/thinkCSpy/chap10.htm which will give an overview of a dictionary. It doesn't explain why dictionary lookup is fast, but we can talk about that later if you want. Please feel free to ask any questions about dictionaries and their use. Learning how to use a dictionary data structure is a skill that pays back extraordinarily well. Good luck! __ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Intro for interfacing with Microsoft Access?
Does anyone know of any online resource that explains how to interface to Microsoft Access via Python, where the intended audience is someone who knows Python, but not the Microsoft innards? I've found http://starship.python.net/crew/bwilk/access.html (which doesn't work for me, and presumably is out of date) and http://www.ecp.cc/pyado.html (which mostly works well enough, but assumes you know Microsoft's Data Access Objects (DAO), and points to the overwhelming Microsoft ADO API Reference. I don't want to do anything too fancy, just read data from my database, make a few calculations and print some summaries obtained from it. I know Python, but not Access (it's my company's DB, not mine) or DAO. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Intro for interfacing with Microsoft Access?
A couple of minutes of googling for 'python odbc' finds the ODBC driver that comes with win32all. It seems to have a fairly simple interface. The download from this page has an example: http://py.vaults.ca/apyllo2.py/D906422565 HTH Kent Terry Carroll wrote: Does anyone know of any online resource that explains how to interface to Microsoft Access via Python, where the intended audience is someone who knows Python, but not the Microsoft innards? I've found http://starship.python.net/crew/bwilk/access.html (which doesn't work for me, and presumably is out of date) and http://www.ecp.cc/pyado.html (which mostly works well enough, but assumes you know Microsoft's Data Access Objects (DAO), and points to the overwhelming Microsoft ADO API Reference. I don't want to do anything too fancy, just read data from my database, make a few calculations and print some summaries obtained from it. I know Python, but not Access (it's my company's DB, not mine) or DAO. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Intro for interfacing with Microsoft Access?
On Fri, 14 Jan 2005, Kent Johnson wrote: A couple of minutes of googling for 'python odbc' finds the ODBC driver that comes with win32all. It seems to have a fairly simple interface. The download from this page has an example: http://py.vaults.ca/apyllo2.py/D906422565 Thanks, Kent. I'm not familiar with OBDC, but I'll look into it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor