Re: [Tutor] python shell not working like it used to
"Jeff Peery" <[EMAIL PROTECTED]> wrote > def __init__(self, other): >d['this'] = other.this > > "other" here is the dictionary I pass in (I think), > so it's for some reason looking for some attribute in > my dictionary called 'this'. other is whatever you pass in. The code expects it to be dictionary like and to have a this attribute > of course my dictionary doesn't have this attribute. So why is your code trying to access one if you know it doesn't exist? And why are you surprised at the error message? (Or is the init() not your code?) > I have no idea what this is. any ideas? Youu seem to have answered your own question. You are passing a dictionary into init() that does not have a this attribute but the code inside the init() is trying to access a this attribute. It can't find one so it raises an error. Either remove the this access in init or add a thus attribute to your dictionary argument. Or pass an argument that does have a this attribute. I'm slightly confused about what you are asking us to tell you? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wav audio playback
"Isaac" <[EMAIL PROTECTED]> wrote > """ > RuntimeWarning: Python C API version mismatch for module _portaudio: > This > Python has API version 1013, module _portaudio has version 1012. > import _portaudio as pa """ > > It does play sound but how can I get rid of this error? You need an updated binary. > Is there another, better, sound playback module that anyone > recommend I > could use? On a Mac you could use the native QuickTime stuff in MacOS. There should be examples on the MacPython mailing list archives and web site. And Apples quickTime documentation is extensive. I suspect you will need the Cocoa extensions but ISTR they come with the MacPython download. Of course that then makes your code Mac dependant. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] miniwiki 1.3 BETA bugs
Kirk Z Bailey wrote: > RE leaves me totally confuzzzeddded. Yep, so confuised I'm having > trouble spelling it. Sp this one line will replace both words and give a > reliable result? > > Barnaby Scott wrote: > [snip] >> No idea if it has anything to do with your problem, but it struck me >> that the iswikiword() function (and processword() which seems to be a >> helper for it) could be replaced with one line, and it would be reliable! >> >> def iswikiword(word): >> return bool(re.match('^([A-Z][a-z]+){2,}$', word)) >> >> Of course you need to import re, but that seems a small price to pay! >> >> HTH >> >> Barnaby Scott >> >> > As far as I know this is 100% reliable - at least it works for me (www.waywood.co.uk/MonkeyWiki/). I suggest you test the function to your own satisfaction - feed it tricky 'possible' WikiWords, and see how it does! I know what you mean - RE syntax is an unruly beast to try and wrestle with, but I *so* glad I made the effort. I don't claim to be anything like an expert, but I now find it very useful indeed. Here's how the function's statement works in case you're interested: bool(re.match('^([A-Z][a-z]+){2,}$', word)) re.match() will look for a match for us, according to the RE given as the first argument, and the string you want to match against as the second ^ means we demand that the pattern matches from the beginning of the string to be tested - we don't want to say yes to anEmbeddedWikiWordLikeThis. (In fact because we are using re.match instead of re.search this is not strictly necessary, but makes it clearer) ([A-Z][a-z]+) means we want a group of letters, starting with a one in the range [A-Z] i.e. a capital, followed by [a-z]+ , meaning one or more lowercase letters ('one or more' is specified by the +). That whole pattern is parenthesised because we want the next element to refer to the whole thing {2,} means we want a match only if our preceding pattern (i.e. a capitalised word) occurs a minimum of 2 times in a row, and a maximum of - well, we don't want to specify a maximum, so we leave it out. (YouMightInFactWantToSpecifyTheMaximumNumberOfWordsThatAreAllowedToAppearInYourWikiLinksToStopPeopleDoingSillyThingsLikeThis). $ means we want a match only if the pattern reaches the end of the test string - i.e. we don't want to match a WordLikeThis62734. As for bool() - nothing to do with RE, but if a match occurs, the result returned by re.match() is a MatchObject instance, otherwise None. I have used bool() to convert these two possible results into True or False though I guess this is not strictly necessary - the truth testing would happen implicitly outside the function anyway. However it seems right to return a boolean if that's what the function's obvious intent is. HTH Barnaby Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionaries and memory handling
Thanks a lot for your replies. Using a dbm seems to be a very good solution in some cases. But most of my dictionaries are nested, and since both keys and values in the dbm 'dictionaries' have to be strings, I can't immediately see how I could get it to work. A bit more detail: I deal with conditional probabilities, with up to 4 parameters. These parameters are numbers or words and determine the value (which is always a number). E.g. I have a dictionary {p1:{p2: {p3:{p4:value, where the p's are different parameters. I sometimes need to sum over one or more of the parameters – for now I have managed to structure the dictionaries so that I only need to sum over the innermost parameter, although this has been a bit cumbersome. regards, Arild Næss Videresendt melding: Fra: " Arild B. Næss " <[EMAIL PROTECTED]> Dato: 23. februar 2007 18.30.40 GMT+01:00 Til: tutor@python.org Emne: [Tutor] dictionaries and memory handling Delivered-To: [EMAIL PROTECTED] Hi, I'm working on a python script for a task in statistical language processing. Briefly put it all boils down to counting different things in very large text files, doing simple computations on these counts and storing the results. I have been using python's dictionary type as my basic data structure of storing the counts. This has been a nice and simple solution, but turns out to be a bad idea in the long run, since the dictionaries become _very_ large, and create MemoryErrors when I try to run my script on texts of a certain size. It seems that an SQL database would probably be the way to go, but I am a bit concerned about speed issues (even though running time is not all that crucial here). In any case it would probably take me a while to get a database up and running and I need to hand in some preliminary results pretty soon, so for now I think I'll postpone the SQL and try to tweak my current script to be able to run it on slightly longer texts than it can handle now. So, enough beating around the bush, my questions are: - Will the dictionaries take up less memory if I use numbers rather than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so: Slightly less, or substantially less memory? - What are common methods to monitor the memory usage of a script? Can I add a snippet to the code that prints out how many MBs of memory a certain dictionary takes up at that particular time? regards, Arild Næss ___ 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] dictionaries and memory handling
Thanks a lot for your replies. Using a dbm seems to be a very good solution in some cases. But most of my dictionaries are nested, and since both keys and values in the dbm 'dictionaries' have to be strings, I can't immediately see how I could get it to work. A bit more detail: I deal with conditional probabilities, with up to 4 parameters. These parameters are numbers or words and determine the value (which is always a number). E.g. I have a dictionary {p1:{p2: {p3:{p4:value, where the p's are different parameters. I sometimes need to sum over one or more of the parameters – for now I have managed to structure the dictionaries so that I only need to sum over the innermost parameter, although this has been a bit cumbersome. regards, Arild Næss Videresendt melding: Fra: " Arild B. Næss " <[EMAIL PROTECTED]> Dato: 23. februar 2007 18.30.40 GMT+01:00 Til: tutor@python.org Emne: [Tutor] dictionaries and memory handling Delivered-To: [EMAIL PROTECTED] Hi, I'm working on a python script for a task in statistical language processing. Briefly put it all boils down to counting different things in very large text files, doing simple computations on these counts and storing the results. I have been using python's dictionary type as my basic data structure of storing the counts. This has been a nice and simple solution, but turns out to be a bad idea in the long run, since the dictionaries become _very_ large, and create MemoryErrors when I try to run my script on texts of a certain size. It seems that an SQL database would probably be the way to go, but I am a bit concerned about speed issues (even though running time is not all that crucial here). In any case it would probably take me a while to get a database up and running and I need to hand in some preliminary results pretty soon, so for now I think I'll postpone the SQL and try to tweak my current script to be able to run it on slightly longer texts than it can handle now. So, enough beating around the bush, my questions are: - Will the dictionaries take up less memory if I use numbers rather than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so: Slightly less, or substantially less memory? - What are common methods to monitor the memory usage of a script? Can I add a snippet to the code that prints out how many MBs of memory a certain dictionary takes up at that particular time? regards, Arild Næss ___ 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] Running an exe from Python
Thanks a lot for all the suggestions. I used the function subprocess.call ( 'c:\abc.exe c:\data\file1'), but as before the command window opens and closes very fast a value of 1 is displayed. How do I see the results?? I am sorry if I sound dumb. Singh On 2/23/07, Alan Gauld <[EMAIL PROTECTED]> wrote: "Rikard Bosnjakovic" <[EMAIL PROTECTED]> wrote >> How can I get python to display >> the results in the interactive window or what is the right way to >> do this. > > Use os.popen: As Rikard, Richard and Hugo have pointed out there are numerous ways to do this in Python. The officially sanctioned way nowadays is to use the subprocess module. It supercedes all tthe previous methods being both more powerful, more flexible and fairly easy to use. All the techniques are discussed in my Using the OS topic in my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ 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] Running an exe from Python
On 2/26/07, Nagendra Singh <[EMAIL PROTECTED]> wrote: Thanks a lot for all the suggestions. I used the function subprocess.call( 'c:\abc.exe c:\data\file1'), but as before the command window opens and closes very fast a value of 1 is displayed. How do I see the results?? I am sorry if I sound dumb. Singh On 2/23/07, Alan Gauld <[EMAIL PROTECTED]> wrote: > > > "Rikard Bosnjakovic" <[EMAIL PROTECTED]> wrote > > >> How can I get python to display > >> the results in the interactive window or what is the right way to > >> do this. > > > > Use os.popen: > > As Rikard, Richard and Hugo have pointed out there are > numerous ways to do this in Python. > > The officially sanctioned way nowadays is to use the subprocess > module. It supercedes all tthe previous methods being both more > powerful, more flexible and fairly easy to use. > > All the techniques are discussed in my Using the OS topic in > my tutorial. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor I am not a big user of python, hence the username, however I used the os.popen command as suggested by Rikard In the shell: data = os.popen('ls') type(data) Then a loop over the data object for f in data: print f seemed to do the job. I did notice that I could not capture the information to a var using the subprocess call - I HAVE NOT READ THE DOCs (yet) - a quick look suggested that this *should* work The call I made using subprocess from subprocess import call foo = call("ls") ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Embedding Python
On Sun, Feb 25, 2007 at 01:35:52PM -0800, Dj Gilcrease wrote: > On 2/25/07, Dave Kuhlman <[EMAIL PROTECTED]> wrote: > > If you have not already, you will want to look at SWIG > > (http://www.swig.org/). SWIG will generate C or C++ code from a > > header file containing structs and classes and function > > declarations. That generated code can then be compiled and linked > > to create a shared library (.so on Linux/UNIX or .dll on Windows), > > which can then be loaded with the Python "import" statement. > > >From what I can tell SWIG cannot be used to create Python modules that > talk to a running C++ app, which is why I am embedding then extending > Python, so the import mymodule will only work while my C++ app is > running A few additional thoughts, hoping to trigger a solution in your mind. SWIG creates Python modules only in the sense that it wraps the existing implementation of a function (or C++ classes) in the C/C++ code needed to expose those functions or classes so that they can be imported and used from Python scripts. But, the implementation of those functions/classes wrapped by SWIG is *still* in C/C++. So they can make calls back into embedding application, as long as they are linked with the embedding application. (Whether you trust your users enough to allow them to make C/C++ calls into your application is an issue you should think about.) One way of enabling *Python* scripts run by an embedding application to communicate back with the embedding C/C++ application is to implement a Python module in C/C++ that makes calls back into the embedding app. For example, if the embedding application contains a function named little_task, then you might implement in C/C++ and expose to Python a module containing a function wrap_little_task, which calls little_task. Then, the embedding C/C++ app can run a Python script which calls wrap_little_task, which in turn calls little_task (which is back in the embedding application). In your case, perhaps, SWIG has wrapped up a function, so that it can be called from Python. That, after all is the point of using SWIG. But, the implementation of that function, whose declaration was wrapped and exposed to Python by SWIG, can call any C/C++ function, even one in the embedding application. One suggestion: Your embedding application runs scripts written in Python which can import and call both functions exposed by the embedding application and functions wrapped by SWIG and can pass values back and forth between them. And don't forget, SWIG has wrapped up a C/C++ function, let's say, so that it can be called from Python. That, after all is the point of using SWIG. But, the *implementation* of that C/C++ function, whose declaration was wrapped and exposed to Python by SWIG, can call any C/C++ function, even one in the embedding application. Hope this helps. And, hope it is not too confused. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running an exe from Python
"Nagendra Singh" <[EMAIL PROTECTED]> wrote > Thanks a lot for all the suggestions. I used the function > subprocess.call ( 'c:\abc.exe c:\data\file1'), but as before > the command window opens and closes very fast > a value of 1 is displayed. How do I see the results?? The result is 1 which indicates an error. You don't want the result you want the outpur, which is a different thing entirely! :-) To get the output you need to access the output stream of the process which is usually stdout. The old way to do that was with os.popen, but the subprocess module provides a new way. The m,odule docs describe how to replace popen using subprocess' Popen class. My tutorial shows an example of the same thing based on the odule documentation. Basically it looks like: import subprocess psout = subprocess.Popen(r'c:\abc.exe c:\data\file1', shell=True, stdout=PIPE).stdout results = psout.read().split('\n') Notice I enclosed the command with a raw string.Otherwise your backslashes get treated as escape characters. This might be why you are getting error codes back?Another way to avoid that is to use forward slashes which Python understands on DOS psout = subprocess.Popen('c:/abc.exe c:/data/file1', shell=True, stdout=PIPE).stdout > I am sorry if I sound dumb. Nope, just looking for the wrong thing. But you only know that after you find out :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Trouble creating DB2 drivers
I'm trying to build the DB2 drivers I downloaded from http://sourceforge.net/projects/pydb2 but I'm getting an error message when I try installing them (after doing "python setup.py install"): Your DB2 root is: C:\Program Files\SQLLIB\ WARNING: it seems that you did not install 'Application Development Kit'. Compilation may fail. running install running build running build_py running build_ext building '_db2' extension C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG "-IC:\Program Files\SQLLIB\include" -IC:\Python25\include -IC:\Python25\PC /Tc_db2_module.c /Fobuild\temp.win32- 2.5\Release\_db2_module.obj _db2_module.c _db2_module.c(24) : fatal error C1083: Cannot open include file: 'sqlcli1.h': No such file or directory error: command '"C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe"' failed with exit status 2 - - - - I can't seem to find anything through Google about the "Application Development Kit" that the error mentions. Can anyone help? ARS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] miniwiki 1.3 BETA bugs
ok, when I have some time to do some coding I will work on trying this. AS is, it is pretty cleaned up, b utg making it less hairy and more definate in it's execution is a Great Good Thing(tm). If the project intrests you I will sip up the current version and leave it on my domain so you can find it. when it is on the4re I will post a link on the list. this may take 2 days, I am being rather busy right now. Barnaby Scott wrote: > Kirk Z Bailey wrote: >> RE leaves me totally confuzzzeddded. Yep, so confuised I'm having >> trouble spelling it. Sp this one line will replace both words and give >> a reliable result? >> >> Barnaby Scott wrote: >> [snip] >>> No idea if it has anything to do with your problem, but it struck me >>> that the iswikiword() function (and processword() which seems to be a >>> helper for it) could be replaced with one line, and it would be >>> reliable! >>> >>> def iswikiword(word): >>> return bool(re.match('^([A-Z][a-z]+){2,}$', word)) >>> >>> Of course you need to import re, but that seems a small price to pay! >>> >>> HTH >>> >>> Barnaby Scott >>> >>> >> > > As far as I know this is 100% reliable - at least it works for me > (www.waywood.co.uk/MonkeyWiki/). I suggest you test the function to your > own satisfaction - feed it tricky 'possible' WikiWords, and see how it > does! > > I know what you mean - RE syntax is an unruly beast to try and wrestle > with, but I *so* glad I made the effort. I don't claim to be anything > like an expert, but I now find it very useful indeed. > > Here's how the function's statement works in case you're interested: > > bool(re.match('^([A-Z][a-z]+){2,}$', word)) > > re.match() will look for a match for us, according to the RE given as > the first argument, and the string you want to match against as the second > > ^ means we demand that the pattern matches from the beginning of the > string to be tested - we don't want to say yes to > anEmbeddedWikiWordLikeThis. (In fact because we are using re.match > instead of re.search this is not strictly necessary, but makes it clearer) > > ([A-Z][a-z]+) means we want a group of letters, starting with a one in > the range [A-Z] i.e. a capital, followed by [a-z]+ , meaning one or more > lowercase letters ('one or more' is specified by the +). That whole > pattern is parenthesised because we want the next element to refer to > the whole thing > > {2,} means we want a match only if our preceding pattern (i.e. a > capitalised word) occurs a minimum of 2 times in a row, and a maximum of > - well, we don't want to specify a maximum, so we leave it out. > (YouMightInFactWantToSpecifyTheMaximumNumberOfWordsThatAreAllowedToAppearInYourWikiLinksToStopPeopleDoingSillyThingsLikeThis). > > > > $ means we want a match only if the pattern reaches the end of the test > string - i.e. we don't want to match a WordLikeThis62734. > > As for bool() - nothing to do with RE, but if a match occurs, the result > returned by re.match() is a MatchObject instance, otherwise None. I have > used bool() to convert these two possible results into True or False > though I guess this is not strictly necessary - the truth testing would > happen implicitly outside the function anyway. However it seems right to > return a boolean if that's what the function's obvious intent is. > > HTH > > > Barnaby Scott > > > > > > > > > -- Salute! -Kirk Bailey Think +-+ | BOX | +-+ knihT Fnord. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Another list comprehension question
I'm probably missing something simple here but is there anyway to accomplish the following with a list comprehension? def get_clists(): return [1, 2, 3] def get_clist(num): if num == 1: return ['a', 'b', 'c'] if num == 2: return ['x', 'y', 'z'] if num == 3: return ['p', 'q'] files = list() for clist in get_clists(): files += get_clist(clist) My first attempt was to try [get_clist(c) for c in get_clists()] but this returns a list of lists rather than the flat list from the original. Any help is appreciate...just trying to be as Pythonesque as possible :-) Jeff ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Another list comprehension question
Smith, Jeff wrote: > I'm probably missing something simple here but is there anyway to > accomplish the following with a list comprehension? > Each element created by a comprehension corresponds to an element returned by the for (if) clause. So we have to find a way for the for clause to return successively 'a', 'b', 'c', 'x', 'y', 'z', 'p', 'q'. The only way I can see to do that is with a generator. Which I think is more work than necessary for your purposes. > def get_clists(): > return [1, 2, 3] > > def get_clist(num): > if num == 1: > return ['a', 'b', 'c'] > if num == 2: > return ['x', 'y', 'z'] > if num == 3: > return ['p', 'q'] > > files = list() > Or just files = [] > for clist in get_clists(): > files += get_clist(clist) > > My first attempt was to try > [get_clist(c) for c in get_clists()] > > but this returns a list of lists rather than the flat list from the > original. > > Any help is appreciate...just trying to be as Pythonesque as possible > :-) > > Jeff > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Another list comprehension question
Hi Jeff, On 27/02/07, Smith, Jeff <[EMAIL PROTECTED]> wrote: > I'm probably missing something simple here but is there anyway to > accomplish the following with a list comprehension? > > def get_clists(): > return [1, 2, 3] > > def get_clist(num): > if num == 1: > return ['a', 'b', 'c'] > if num == 2: > return ['x', 'y', 'z'] > if num == 3: > return ['p', 'q'] This would be better represented as a dictionary: >>> clists = { 1:['a', 'b', 'c'], ...2:['x', 'y', 'z'], ...3:['p', 'q'] } You may also be able to replace get_clists() with a call to clists.keys() (or just simple iteration), depending on what you are doing. >>> for k in clists: ... print clists[k] ... ['a', 'b', 'c'] ['x', 'y', 'z'] ['p', 'q'] > files = list() > for clist in get_clists(): > files += get_clist(clist) Just a comment -- you could write this as "files.extend(get_clist(clist))", which would be slightly more efficient. > My first attempt was to try > [get_clist(c) for c in get_clists()] > > but this returns a list of lists rather than the flat list from the > original. This will do it: >>> [x for k in clists for x in clists[k]] ['a', 'b', 'c', 'x', 'y', 'z', 'p', 'q'] Or [x for k in get_clists() for x in get_clist(k)] using your original structure. HTH! -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python shell not working like it used to
well the __init__() funciton is not my code, it is in: C:\Python24\Lib\site-packages\wx-2.6-msw-unicode\wx\py\shell.py as I mentioned I upgraded wxpython... maybe I should email there... anyhow I just want to use my dictionary in the shell, but I'm not sure what the attribute 'this' is... it seems to be something different from my previous version of wxpython. thanks. J Alan Gauld <[EMAIL PROTECTED]> wrote: "Jeff Peery" wrote > def __init__(self, other): >d['this'] = other.this > > "other" here is the dictionary I pass in (I think), > so it's for some reason looking for some attribute in > my dictionary called 'this'. other is whatever you pass in. The code expects it to be dictionary like and to have a this attribute > of course my dictionary doesn't have this attribute. So why is your code trying to access one if you know it doesn't exist? And why are you surprised at the error message? (Or is the init() not your code?) > I have no idea what this is. any ideas? Youu seem to have answered your own question. You are passing a dictionary into init() that does not have a this attribute but the code inside the init() is trying to access a this attribute. It can't find one so it raises an error. Either remove the this access in init or add a thus attribute to your dictionary argument. Or pass an argument that does have a this attribute. I'm slightly confused about what you are asking us to tell you? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor - Everyone is raving about the all-new Yahoo! Mail beta.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Another list comprehension question
John Fouhy wrote: [snip] > > Or [x for k in get_clists() for x in get_clist(k)] using your original > structure. > Well I learned something! -- Bob Gailer 510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] isinstance -> instance
Hello, Following the guidelines here, at the bottom of the page: http://www.python.org/dev/peps/pep-0008/ I'm using isinstance() to test the type of some data. Now the thing is that, what is the name to use for a class instance? For example, say I run this: class A: def __init__( self ): self.a = 'a' a = A() print type( a ) Outputs: Now if I test against the instance type like I would for integer, strings and the likes: isinstance( a, instance ) Outputs: NameError: name 'instance' is not defined So I'm a bit at a loss here. I don't want to know if the instance is an instance of a specific class, I just want to know if it's an instance. Thanks Bernard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] FW: isinstance -> instance
Oops...I replied instead of replied all. > -Original Message- > From: Mike Hansen > Sent: Monday, February 26, 2007 2:43 PM > To: 'Bernard Lebel' > Subject: RE: [Tutor] isinstance -> instance > > > > > -Original Message- > > From: [EMAIL PROTECTED] > > [mailto:[EMAIL PROTECTED] On Behalf Of Bernard Lebel > > Sent: Monday, February 26, 2007 2:34 PM > > To: Tutor > > Subject: [Tutor] isinstance -> instance > > > > Hello, > > > > Following the guidelines here, at the bottom of the page: > > http://www.python.org/dev/peps/pep-0008/ > > > > I'm using isinstance() to test the type of some data. > > Now the thing is that, what is the name to use for a class instance? > > > > For example, say I run this: > > > > class A: > > def __init__( self ): > > self.a = 'a' > > > > a = A() > > > > print type( a ) > > > > Outputs: > > > > > > > > > > > > Now if I test against the instance type like I would for integer, > > strings and the likes: > > > > isinstance( a, instance ) > > > > Outputs: > > NameError: name 'instance' is not defined > > > > > > So I'm a bit at a loss here. I don't want to know if the instance is > > an instance of a specific class, I just want to know if it's an > > instance. > > > > > > Thanks > > Bernard > > Shouldn't that be > > isinstance(a, A) > > ? > > Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: isinstance -> instance
That's fine, but that tells me that 'a' is an instance of 'A'. It doesn't, however, tell me if 'a' is an instance or the actual class object. Thanks Bernard On 2/26/07, Mike Hansen <[EMAIL PROTECTED]> wrote: > Oops...I replied instead of replied all. > > > -Original Message- > > From: Mike Hansen > > Sent: Monday, February 26, 2007 2:43 PM > > To: 'Bernard Lebel' > > Subject: RE: [Tutor] isinstance -> instance > > > > > > > > > -Original Message- > > > From: [EMAIL PROTECTED] > > > [mailto:[EMAIL PROTECTED] On Behalf Of Bernard Lebel > > > Sent: Monday, February 26, 2007 2:34 PM > > > To: Tutor > > > Subject: [Tutor] isinstance -> instance > > > > > > Hello, > > > > > > Following the guidelines here, at the bottom of the page: > > > http://www.python.org/dev/peps/pep-0008/ > > > > > > I'm using isinstance() to test the type of some data. > > > Now the thing is that, what is the name to use for a class instance? > > > > > > For example, say I run this: > > > > > > class A: > > > def __init__( self ): > > > self.a = 'a' > > > > > > a = A() > > > > > > print type( a ) > > > > > > Outputs: > > > > > > > > > > > > > > > > > > Now if I test against the instance type like I would for integer, > > > strings and the likes: > > > > > > isinstance( a, instance ) > > > > > > Outputs: > > > NameError: name 'instance' is not defined > > > > > > > > > So I'm a bit at a loss here. I don't want to know if the instance is > > > an instance of a specific class, I just want to know if it's an > > > instance. > > > > > > > > > Thanks > > > Bernard > > > > Shouldn't that be > > > > isinstance(a, A) > > > > ? > > > > Mike > ___ > 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] FW: isinstance -> instance
On 2/26/07, Bernard Lebel <[EMAIL PROTECTED]> wrote: > That's fine, but that tells me that 'a' is an instance of 'A'. > It doesn't, however, tell me if 'a' is an instance or the actual class object. It doesn't? >>> class A: pass >>> a = A() >>> isinstance(a, A) True >>> isinstance(A, A) False If you want to know if a is an instance of any type, try this: >>> import types >>> isinstance (a, types.InstanceType) True I'm pretty sure that types.InstanceType only works on old-style classes. I believe you can check for an instance of a new-style class with: isinstance(a, object) -- Jerry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] isinstance -> instance
"Bernard Lebel" <[EMAIL PROTECTED]> wrote > class A: >def __init__( self ): >self.a = 'a' > > a = A() > > print type( a ) > > Outputs: > So use types.Instancetype import types as t >>> class A: pass ... >>> a = A() >>> type(a) >>> type(A) >>> type(a) == t.InstanceType True >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: isinstance -> instance
Bernard Lebel wrote: > That's fine, but that tells me that 'a' is an instance of 'A'. > It doesn't, however, tell me if 'a' is an instance or the actual class object. I'm not sure what you are trying to do. In [1]: class A: pass ...: In [2]: a=A() In [3]: isinstance(a, A) Out[3]: True In [4]: isinstance(A, A) Out[4]: False The actual class object is not an instance of itself. So I'm a bit at a loss here. I don't want to know if the instanceis an instance of a specific class, I just want to know if it's an instance. *Everything* in Python is an instance of *some* class. int, str, classes themselves, modules, etc. Everything is an instance of something. The specific is the type of instances of old-style classes. There is some funny business going on that I don't fully understand but AFAIK instances of old-style classes are in some sense all instances of this . If you are trying to test whether an object is an instance of an old-style class you can do it like this (though I can't imagine why you would want to): In [10]: class C: : pass : In [11]: c=C() In [12]: isinstance(c, type(a)) Out[12]: True Or you can import types and check against types.InstanceType: In [13]: import types In [14]: dir(types) In [15]: isinstance(c, types.InstanceType) Out[15]: True Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: isinstance -> instance
Jerry Hill wrote: > I believe you can check for an instance of a new-style class > with: > isinstance(a, object) I'm not sure if that will ever fail. Given values from my previous post, I get: In [16]: isinstance(a, object) Out[16]: True In [17]: isinstance(A, object) Out[17]: True In [18]: isinstance(b, object) Out[18]: True In [19]: isinstance(types, object) Out[19]: True In [20]: def f(): pass : In [21]: isinstance(f, object) Out[21]: True Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: isinstance -> instance
Okay. right now I'm using types.InstanceType approach. To elaborate on the context of my question, I have this module whose only job is to test an object against a large array of types. The thing is that I never know in advance what is going to be the data, and it could be just about anything (string, int, float, bool, class object, class instance, etc), and I never in advance against what type it will be tested. Plus, in case the data is an instance of a class I have coded, the module never knows what is the actual class object the instance is obtained from. Only the functions making call to this module "know" what they expect from the module. There are countless of such functions, and each has its own specificities. So I'm aiming as a generic code as possible, where only the type of the object is relevant, without any need for additional data. Thanks Bernard On 2/26/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > Jerry Hill wrote: > > I believe you can check for an instance of a new-style class > > with: > > isinstance(a, object) > > I'm not sure if that will ever fail. Given values from my previous post, > I get: > In [16]: isinstance(a, object) > Out[16]: True > In [17]: isinstance(A, object) > Out[17]: True > In [18]: isinstance(b, object) > Out[18]: True > In [19]: isinstance(types, object) > Out[19]: True > In [20]: def f(): pass > : > In [21]: isinstance(f, object) > Out[21]: True > > Kent > ___ > 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] Group sequence pairwise
>>> a = list('asdfg') >>> map(None, a[::2], a[1::2]) [('a', 's'), ('d', 'f'), ('g', None)] >>> a = list('asdfgh') >>> map(None, a[::2], a[1::2]) [('a', 's'), ('d', 'f'), ('g', 'h')] >>> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about profile.run() and decorators
To whom it may concern, I was directed to this forum... I searched for 'decorator profile' in the Python tutorial archives, and had no hits, so I hope this is not a lame question. Is there a way to construct a string version (suitable to pass into profile.run()) from what is available inside a decorator function? I realize that what I am trying to do could probably be done otherwise, but this arose out of questions and problems possed in a Python class I just completed, and I am still trying to find my way around the language. My 'best' attempt is shown below. Also, I have limited myself to a function with only 1 parameter, but it seems to get even worse if you have 2 or more arguments, since repr() takes only a single argument. BTW, I am using ActiveState Python 2.4.3 on Windows XP. Any and all suggestions or solutions welcomed. Thank you. Cheers, - Thane =-=-= import profile def myProfileDecorator(function): def newFunction(obj, *args): # This attempt does not seem to give an object expression that can be used #expression = function.__name__ + '(' + repr(obj) + ',' + repr(*args) + ')' # This attempt generates a NameError exception expression = function.__name__ + '(' + repr(*args) + ')' print 'About to call: profile.run(', expression, ')' profile.run(expression) return newFunction import random class Foo: @myProfileDecorator def results(x): print str(x) + " Done" x = Foo() print x.results("Almost") =-=-= ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about profile.run() and decorators
[EMAIL PROTECTED] wrote: > Is there a way to construct a string version (suitable to pass > into profile.run()) from what is available inside a decorator function? > I realize that what I am trying to do could probably be done otherwise, > but this arose out of questions and problems possed in a Python class I > just completed, and I am still trying to find my way around the > language. My 'best' attempt is shown below. Take a look at profile.Profile.runcall() (look at the source for profile, it is not in the docs). This function takes an actual function object as its parameter rather than a string describing the function call. Kent > > Also, I have limited myself to a function with only 1 parameter, > but it seems to get even worse if you have 2 or more arguments, since > repr() takes only a single argument. > > BTW, I am using ActiveState Python 2.4.3 on Windows XP. > > Any and all suggestions or solutions welcomed. > > Thank you. > > Cheers, > > - Thane > > =-=-= > > import profile > > def myProfileDecorator(function): > def newFunction(obj, *args): > # This attempt does not seem to give an object expression that can > be used > #expression = function.__name__ + '(' + repr(obj) + ',' + > repr(*args) + ')' > > # This attempt generates a NameError exception > expression = function.__name__ + '(' + repr(*args) + ')' > > print 'About to call: profile.run(', expression, ')' > profile.run(expression) > return newFunction > > import random > > class Foo: > @myProfileDecorator > def results(x): > print str(x) + " Done" > > x = Foo() > > print x.results("Almost") > > =-=-= > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor