Re: is it a bug in Module copy or i am wrong??
On Thu, Nov 6, 2008 at 11:59 PM, yoma <[EMAIL PROTECTED]> wrote: > python version 2.5 in module copy > > we all know that copy have two method: copy() and deepcopy(). > and the explain is > - A shallow copy constructs a new compound object and then (to the > extent possible) inserts *the same objects* into it that the > original contains. > > - A deep copy constructs a new compound object and then, recursively, > inserts *copies* into it of the objects found in the original. > > so i try a example: > import copy > > class A: >i = 1 > > class B: >a = A() Note that `a` is a class variable, not an instance variable. This ends up being important. > > > b = B() > > x=copy.copy(b) > > y=copy.deepcopy(b) I believe these only copy the instance variables of `b`. They do NOT copy the class `B` (IMHO, copying B would be weird and unexpected behavior here anyway) or its constituent variables, such as `a`. > > print id(x.a), id(b.a) > > print id(y.a), id(y.a) > > the result: > 14505264 14505264 > 14505264 14505264 Thus this makes sense. These all refer to B's variable `a`, which is a class variable and therefore not copied by copy() or deepcopy()-ing `b`, an *instance* of class B. The fact that you can access `a` through B instances does not mean that `a` "belongs" to any instance of B and is merely a result of how Python's object system works. Disclaimer: I am not a CPython dev and did not look at the `copy` module's sources. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > So maybe i have a wrong understand to deep copy and shallow copy or > it is a bug ? > > please help me!! > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: [urllib2 + Tor] How to handle 404?
On Fri, Nov 7, 2008 at 12:05 AM, Gilles Ganault <[EMAIL PROTECTED]> wrote: > Hello > >I'm using the urllib2 module and Tor as a proxy to download data > from the web. > > Occasionnally, urlllib2 returns 404, probably because of some issue > with the Tor network. This code doesn't solve the issue, as it just > loops through the same error indefinitely: > > = > for id in rows: >url = 'http://www.acme.com/?code=' + id[0] >while True: >try: >req = urllib2.Request(url, None, headers) >response = urllib2.urlopen(req).read() >except HTTPError,e: >print 'Error code: ', e.code >time.sleep(2) >continue else: #should align with the `except` break handle_success(response) #should align with `url =` line Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > = > > Any idea of what I should do to handle this error properly? > > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Very simple - please help
On Fri, Nov 7, 2008 at 8:52 PM, pineapple <[EMAIL PROTECTED]> wrote: > I am not a python programmer, but am being forced to port one of my > (smalltalk) applications to python for pragmatic reasons (python is > embedded with a graphics package I am switching over to, so to use the > graphics package I am essentially forced to use python). Okay, enough > background. > > At any rate, in my smalltalk solution, in order to avoid an if-then- > else chain of "if this command, do this function, else if this command > do another function..." I have commands set up in a dictionary. I > read the command integer, then key it into the dictionary to see what > method/function to call. > > #Conceptual representation of dictionary with keys and values: > > 1: do_command1 > 2: do_command2 > 3: etc... > > Trying to set up the same thing in python, it seems the lambda > expression is what I need. So I set up a simple class to test this, > with some simple code as follows: > > ### > class Blah(list): >pass > > commands = {1: (lambda: Blah())} > ### > > This is accepted by the interpreter, no problem. If I type "commands" > into the interpreter I get the dictionary back showing the key '1' > attached to the lambda expression. If I type "commands[1]" into the > interpreter, I get the lambda function back. However, when I try to > invoke the lambda function with a "commands[1]()", I get a "global > name 'Blah' is not defined." I find this error odd, because if I do a > "Blah()", I get back a "[]" as expected (a list). The code you gave works perfectly: chris ~ $ python Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class Blah(list): ... pass ... >>> commands = {1: (lambda: Blah())} >>> commands[1]() [] Please post some of the actual code so that we can determine the problem. Taking a guess, I'd suspect Blah and commands are in different modules and you didn't import Blah into commands' module, hence why Python can't find it. But we'd need some more details to be able to determine that. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > For a day, I have tried everything under the sun I know to try. For > instance, I thought perhaps lambdas don't work with methods, so I > wrapped the method call in a function. But I get the same error. I > have spent a day online googling this error, but have found nothing to > help me. > > Can a guru out there help a python newbie with this? I figure you can > spot the problem in, oh, 5 seconds or less? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing characters within a string
On Sat, Nov 8, 2008 at 9:16 PM, John Smith <[EMAIL PROTECTED]> wrote: > Hi, > > I coded a python script that lets me parse a csv file into html code with a > certain format, but I would like to replace every "<" and ">" character that > appears within each column entry of the csv file (they are parsed as > strings) with the html equivalents of "<" and ">". You want the cgi.escape() function - http://docs.python.org/library/cgi.html#cgi.escape Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > example csv file row: > "FIXED","All","Enable entry" > > and I want to replace with
Re: break up a value in a list to a list of individual items
On Sun, Nov 9, 2008 at 2:38 AM, r3bol <[EMAIL PROTECTED]> wrote: > Hi, sorry to post this, but I've had a really hard time finding how to > do it. > Q. > How can I break up a value in a list to a list of individual items > (preferably without importing any modules)? > Like... > ['12345'] (string) > to > [1, 2, 3, 4, 5] [numbers] nums = [int(char) for char in '12345'] Note also that: list("1234") == ["1", "2", "3", "4"] And do be sure to read one of the several fine Python tutorials. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: [Newbie] Strange output from list
On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault <[EMAIL PROTECTED]> wrote: > On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <[EMAIL PROTECTED]> wrote: >>sql = 'SELECT id FROM master' >>rows=list(cursor.execute(sql)) >>for id in rows: >> sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0] >> result = list(cursor.execute(sql)) >> print "Code=%s, number=%s" % (id[0],result[0][0]) Using liberal "term rewriting", consider the following rough equivalencies in the code: id[0] <==> rows[INDEX_HERE][0] <==> list(cursor.execute(sql))[INDEX_HERE][0] result[0][0] <==> list(cursor.execute(sql))[0][0] Note that in both cases, the list is sliced twice; the for-loop just conceals the `[INDEX_HERE]` implicit slicing that is caused by iterating over the list. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com >>Notice the extra [0] index on the "result" >> >>In English: >>Item zero of the tuple that is item zero of result > > Thanks, it worked. But why does "id[0]" return the value of the first > (and only) column as I expected it, while I need to use "result[0] > [0]" to access the first column? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing a "status " line from a python script
On Tue, Nov 11, 2008 at 11:02 AM, Chris Seymour <[EMAIL PROTECTED]> wrote: > Hi All, > I am working on a python script for my colleague that will walk a > directory and search in the different files for a specific string. > These pieces I am able to do. What my colleague wants is that when > she runs the script the filename is replaced by the current file that > is being processed. So instead of seeing a series of files being > listed down the page, she only wants to see the file currently being > processed. > > I am not sure if this is even possible. Any thoughts would be greatly > appreciated. Have you tried using carriage returns ("\r")? chris ~ $ python Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> for i in range(10): ... print '\r'+str(i), 9 >>> Note how each line gets overwritten by the next so that we only see the final number output (9). But really, I don't see a good reason to do this. So what, the output takes up some extra lines on the terminal? Big whoop. Your colleague can either pipe the script to `less` or a file if it really bothers them. And that way you get a list of all files processed, which can often come in handy in my experience. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks. > > Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Close access to the base class public methods
On Tue, Nov 11, 2008 at 11:16 AM, RinKaMeAri <[EMAIL PROTECTED]> wrote: > On Nov 11, 9:12 pm, Steve Holden <[EMAIL PROTECTED]> wrote: >> RinKaMeAri wrote: >> > Hi! >> > Could you imagine any way to block access to the base class public >> > methods? >> > Here is an example: >> > class B: >> > def public_method(): >> > pass >> >> > class A(B): >> > def public_a_method(): >> > pass >> >> > def a = A() >> >> > Is there any way to block the call a.public_method() without any >> > changes to B class? >> > Thank you! >> >> The simplest way would be to override B.public_method within A by >> defining A.public_method to raise a NotImplementedError or similar >> exception. Though of course this then begs the question of why A would >> need to subclass B in the first place, but I assume there would be >> methods you *did* want to implement. >> > > BTW, what do you mean "to subclass B in the *first place*"? Because you're inheriting from A and yet you don't want to inherit a certain part of A, in this case public_method(), it's usually a sign something is wrong with your class hierarchy; otherwise, you could just inherit from something else which would have just the part of A you want to inherit; it's a so-called "code smell", specifically Refused Bequest I believe. See this link into Fowler's Refactoring for more info on Refused Bequest and the other code smells: http://books.google.com/books?id=1MsETFPD3I0C&pg=PA87&lpg=PA87&dq=refused+bequest&source=bl&ots=pKN4o0QJc7&sig=rYT4lfWxhKijvNHpLYqk8DY5Epw&hl=en&sa=X&oi=book_result&resnum=3&ct=result Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple breaks
On Thu, Nov 13, 2008 at 2:07 AM, TP <[EMAIL PROTECTED]> wrote: > Hi everybody, > > Several means to escape a nested loop are given here: > > http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python > > According to this page, the best way is to modify the loop by affecting the > variables that are tested in the loops. Otherwise, use exception: > > "If, for some reason, the terminating conditions can't be worked out, > exceptions are a fall-back plan." > > In the following example, is this possible to affect the two iterators to > escape the two loops once one "j" has been printed: > Non-exception alternative: done = False > for i in range(5): >for j in range(i): > print j done = True break > # I would type "break 2" in shell bash > # In C, I would set j=i-1 and i=4 > # In Python, is this possible to affect the two iterators? if done: break > > Or the only means is to use exception? No, you could add a boolean variable and a break condition like above. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance > > Julien > > -- > python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z > (55l4('])" > > "When a distinguished but elderly scientist states that something is > possible, he is almost certainly right. When he states that something is > impossible, he is very probably wrong." (first law of AC Clarke) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest exits
On Thu, Nov 13, 2008 at 11:01 AM, Alan Baljeu <[EMAIL PROTECTED]> wrote: > When I call unittest.main(), it invokes sys.exit(). I would like to run > tests without exiting. How can I? There's probably a better way that stops it from trying to exit in the first place, but here's a quick kludge: try: unittest.main() except SystemExit: pass sys.exit() does its job by noting the return code and then raising the SystemExit exception, which you are free to catch. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > Alan Baljeu > > > __ > Instant Messaging, free SMS, sharing photos and more... Try the new Yahoo! > Canada Messenger at http://ca.beta.messenger.yahoo.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: To throw or to throw not?
On Thu, Nov 13, 2008 at 5:11 PM, Emanuele D'Arrigo <[EMAIL PROTECTED]> wrote: > I'm pondering on what is a bit of a philosophical dilemma. > When should I throw an exception and when should I not? > > Suppose I have myFunc1() calling myFunc2() which in turn calls myFunc3 > (). > Suppose myFunc3() has detected a problem. What should it do? > > Throw an exception, forcing myFunc2() to handle it and/or trigger > another exception for myFunc1() to deal with? Or should it simply > return a meaningful error code, for myFunc2() and myFunc1() to handle > as an option but not forcing them to do so? Depends on how serious the error is (e.g. str.find() returns -1 rather than raising an exception if it can't find the substring), but 98% of the time, you'll want to raise an exception; it's Pythonic, idiomatic, and expected. You'd have to have a *really* good reason to use an error value/code instead. Python is not C, and despite what Joel has said On Software, error codes generally suck. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Manu > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: email notifier question ??
2008/11/13 yoma <[EMAIL PROTECTED]>: > hi guys! >I want to use python send an email to acceptor. And i hope to > receive the message that the acceptor has read my email. > > So how to realize that get the message? To send an email using Python, you'll need to use the `smtplib` module: http://docs.python.org/library/smtplib.html#module-smtplib You'll have to check the relevant standards/specs related to email for how to request a return receipt from the recipient in the message you send. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Sort dictionary by value when value is a list
On Fri, Nov 14, 2008 at 10:26 AM, major-john <[EMAIL PROTECTED]> wrote: > I'm having trouble sorting a dictionary based on values when the values are > all lists, and i want to sort the list by key with the largest value lists > in decreasing size. > > Currently, I have the following: > > from operator import itemgetter > > dict = {'A': [(10, 20), (12, 18), (5, 11), (18, 25)], 'C': [(1, 200)], 'B': > [(1, 10), (100, 200), (150, 300), (250, 350), (300, 400)], 'D': [(3, 400)]} > > I have tried several methods, and seem to have come closest using: > > sorted(self.dict.items(), key=itemgetter(1), reverse=True) > > My problem is that this will return the key order A,D,C,B > The order I want is based on the size of the lists each key points to: > B,A,D,C or B,A,C,D > > Question: > itemgetter(1) is just returning the value, which is a list. How do I > specify that I want the values to be sorted by list size? You just need to add a call to len() in the key function: sorted(self.dict.items(), key=lambda pair: len(pair[1]), reverse=True) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks! > john > > > > > > -- > "We are healthy only to the extent that our ideas are humane." --Killgore > Trout > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsubscriptable object when using Exec
On Fri, Nov 14, 2008 at 10:40 AM, Indian <[EMAIL PROTECTED]> wrote: > Hi Friends > > I'm getting the TypeError Unsubscriptable object when using Exec in a class > > Here's the example > > class Fake(object): > def __init__(self, reg): > self._reg = reg > > def OpenKey(self, rootkey, path): > open_key = self._reg > path_string='[\'HKLM\']' > for key in path.split('\\'): > path_string += '[\'%s\']'%key > a='d=open_key%s'%path_string > exec(a) > return d > > When i create a claassobject and call the method Openkey i get the above > error but it works fine in the below example without class > > def OpenKey(rootkey, path, reg): > open_key = reg > path_string='[\'HKLM\']' > for key in path.split('\\'): > path_string += '[\'%s\']'%key > a='d=open_key%s'%path_string > print a > exec(a) > return d You don't need and shouldn't be using `exec` here. It appears as though you're just doing the following in a much more obtuse and unnecessarily complicated manner: def OpenKey(rootkey, path, reg): open_key = reg['HKLM'] for key in path.split('\\'): open_key = open_key[key] return open_key Lesson: Don't use `exec`. More importantly, what led you to think you needed to use it here in the first place? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > What am i doing wrong in the class?Any thought on this would be helpful :) > > Thanks in Advance > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help in understanding a python code
On Sat, Nov 15, 2008 at 8:41 PM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I am trying to understand the following line: > # a is an integer array > > max([(sum(a[j:i]), (j,i)) This code isn't valid. You have a [ with no closing ]. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Can you please tell me what that means, > I think sum(a[j:i] means find the some from a[j] to a[i] > But what is the meaning of the part (j,i)? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Customizing sequence types
On Sun, Nov 16, 2008 at 8:16 AM, Mr. SpOOn <[EMAIL PROTECTED]> wrote: > Hi, > I'm trying to create a class which inherit a list to change some behavior. > This list should contain other instance objects and has to manage > these instances in a particular way. > > 1) I need to sort this elements in this list, but they must be sorted > using an instance variable. What does Python use to sort elements? I > mean, there is a __sort__ method in the class list or it just uses > comparison operators? In this case, shall I just redefine this > operators in the element classes? It uses the comparison operators. IIRC, at a minimum it needs __lt__ and __eq__ to be defined on the elements. > > 2) I need to have just unique elements. Maybe this is related to first > question (or maybe not). Again, to estabilish the uniqueness of an > element I have to use an instance variable. I think I have to rewrite > both the methods append() and __contains__(), but I'm not sure how. > > For the first one I did: > >def append(self, element): >if element in self: >pass >else: >list.append(self, element) You should probably use the `bisect` module (http://docs.python.org/library/bisect.html) for searching and inserting into the list as it takes advantage of and ensures that the list keeps sorted. It also means that __contains__ and some other operations become O(log N) rather than O(N). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > It seems right to me, but I have no idea what to do with __contains__() > > Suggestion? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional parameter object re-used when instantiating multiple objects
On Sun, Nov 16, 2008 at 11:02 AM, George Sakkis <[EMAIL PROTECTED]> wrote: > On Nov 16, 8:28 am, Steve Holden <[EMAIL PROTECTED]> wrote: >> >> > +1. Understanding and accepting the current behavior (mainly because >> > of the extra performance penalty of evaluating the default expressions >> > on every call would incur) is one thing, claiming that it is somehow >> > natural is plain silly, as dozens of threads keep showing time and >> > time again. For better or for worse the current semantics will >> > probably stay forever but I wish Python grows at least a syntax to >> > make the expected semantics easier to express, something like: >> >> > def foo(bar=`[]`): >> > bar.append(6) >> >> > where `expr` would mean "evaluate the expression in the function >> > body". Apart from the obvious usage for mutable objects, an added >> > benefit would be to have default arguments that depend on previous >> > arguments: >> >> Would you also retain the context surrounding the function declaration >> so it's obvious how it will be evaluated, or would you limit the default >> values to expressions with no bound variables? > > No, all expressions would be allowed, and the semantics would be > identical to evaluating them in the function body; not context would > be necessary. > >> > def foo(x, y=`x*x`, z=`x+y`): >> > return x+y+z >> >> > as opposed to the more verbose and less obvious current hack: >> >> > def foo(x, y=None, z=None): >> > if y is None: y = x*x >> > if z is None: z = x+y >> > return x+y+z >> >> "Less obvious" is entirely in the mind of the reader. > > Without documentation or peeking into the function body, a None > default conveys little or no information, so I don't think it's just > in the mind of the reader. Do you find the following less obvious than > the current workaround ? > > from datetime import date > from timedelta import timedelta > > def make_reservation(customer, > checkin=`date.today()`, > checkout=`checkin+timedelta(days=3)`): > ... > > >> However I can see >> far more justification for the behavior Python currently exhibits than >> the semantic time-bomb you are proposing. > > I didn't propose replacing the current behavior (that would cause way > too much breakage), only adding a new syntax which is now invalid, so > one would have to specify it explicitly. Minor FYI, but Guido has proscribed backticks ever being used in Python again. See http://www.python.org/dev/peps/pep-3099/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > George > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional parameter object re-used when instantiating multiple objects
For the Nth time this year that this has come up, I'll point out yet again that this issue has already been discussed to death before: [Python-ideas] proto-PEP: Fixing Non-constant Default Arguments http://mail.python.org/pipermail/python-ideas/2007-January/000121.html [Python-3000] pre-PEP: Default Argument Expressions http://mail.python.org/pipermail/python-3000/2007-February/005704.html Result: Evaluating the arguments at runtime rather than definition-time was deemed too magical; the backward compatibility issues make changes unlikely; it's hard to find an acceptable syntax. But hey, if some people want to have another go at it, best of luck. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com On Sun, Nov 16, 2008 at 8:11 PM, alex23 <[EMAIL PROTECTED]> wrote: > On Nov 17, 12:27 pm, Steve Holden <[EMAIL PROTECTED]> wrote: >> If multiple statements are needed to perform the >> argument initialization, how would you then propose the problem should >> be solved? > > Why, with another function of course! > > def f(x, y=`f_arg_computation(x)`): ... > > Or my personal favourite: > > def f(x, **`f_arg_computation(x)`): ... > > Seriously, though, I agree with Steve; the function body -is- the > place for computation to occur. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Its Libraries--Who's on First?
On Sun, Nov 16, 2008 at 9:25 PM, W. eWatson <[EMAIL PROTECTED]> wrote: > Is there some repository that says something like for Python 2.5 it works > with: > > Win OSes: W2K, XP, Vista For the supported OSes, check the links for the versions on http://python.org/download/ and see whether downloads are offered for that OS (version). > numpy vers y, matplotlib vers x. scipy z, etc. For arbitrary third-party packages, check their websites to see which versions are compatible with which versions of Python. No one makes some centralized compatibility matrix for the cartesian product of python, OS, and third-party library versions. Probably because, as you can imagine, it would be enormously tedious. Also, I doubt it would even be all that useful to most developers as they simply go with whatever version of Python their package's specific third-party libraries require, with OS compatibility being a non-issue. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > W. eWatson > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39° 15' 7" N, 121° 2' 32" W, 2700 feet > >Web Page: > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting lists
On Mon, Nov 17, 2008 at 1:56 AM, asc <[EMAIL PROTECTED]> wrote: > Hi all, > I have a problem and I'm not sure whether sort() can help me. > I understand that if I have a list; say L = ['b', 'c', 'a'] > I can use L.sort() and I will then have; L = ['a', 'b', 'c'] > > But my problem is this. I have a list, that contains a number of > embeded lists; > e.g. L2 = [['something', 'bb'], ['somethingElse', 'cc'], > ['anotherThing', 'aa']] > Now I want to sort this list by the second item of each sublist. So > the outcome I would like is; > L2 = [['anotherThing', 'aa'], ['something', 'bb'], ['somethingElse', > 'cc']] > > Is there a way I can use sort for this? Or am I going to have write a > custom function to sort this out? You use the `key` argument to .sort(): L2.sort(key=lambda item: item[1]) This sorts L2 by the result of applying the `key` function to each of the items. Behind the scenes, I believe it does a Schwartzian transform. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Many thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Best practise hierarchy for user-defined exceptions
On Mon, Nov 17, 2008 at 3:47 AM, Slaunger <[EMAIL PROTECTED]> wrote: > Hi there, > > I am a newcomer to Pyhton coming from Java working on a relatively > large Pyhton project with several packages and modules. To improve > exception handling I would like to introduce some user-defined > exceptions to distinguish between exceptions raised in self-written > code as compared to std libray modules used there-in. > > Say, for instance I would like to define a MyParseError exception to > indicate that something has gone wrong while parsing a byte string, a > file, or while packing into or unpacking from a struct.Struct > instance. > > Here is my stub-implemented idea on how to do it so far, which is > inspired by how I would have done it in Java (but which may not be > very Pythonic??): > > class MyException(Exception): > >pass > The above class probably isn't necessary. You don't need to overgeneralize this much. > class MyStandardError(MyException, StandardError): > >pass Rename the previous class to just MyError in light of removing the other class. > > class MyParseError(MyStandardError, ValueError): > > pass This technique is very Pythonic. Subclass from both the exception class for your module and from a built-in one if there's an applicable one. > > Some comments and questions > > 1. The hierarchy is deliberately deep and maps to the std library such > that it is easier to extend Zen of Python: Flat is better than nested. This is part of the reason I recommend removing the one class. > 2. The implementations are empty but can be extended with hook for > logging, statistics, etc. True of stubs in general... > 3. I use multiple inheritance in the two sub-classes. I have not tried > that before. Is this A Good Thing or A Bad Thing to do? Good in this case, just be careful to use super() if you override any methods. > 4. Which __xx__ methods would you normally implement for the user- > defined exception classes? I was thinking of __str__, for example? Is > there a recommended __str__ idiom to use for that? You might override __init__ if you want to store additional information about the cause of the exception (e.g. location of parse error, name of the rule the error occurred in, etc). The __str__ inherited from Exception is usually sufficient, but you can override it if you want to. it's a judgement call IMHO. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- Slaunger > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Customizing sequence types
On Mon, Nov 17, 2008 at 10:05 AM, Mr. SpOOn <[EMAIL PROTECTED]> wrote: > It seems that I solved my main problem, but I still have some doubt. > > I'll make an example: > class foo: > ...def __init__(self, a): > ...self.a = a > ... f = foo(1) f2 = foo(2) f3 = foo(3) f1 = foo(1) s = set() s.add(f) s > set([<__main__.foo instance at 0x8311fac>]) s.add(f2) s.add(f3) s.add(f1) s > set([<__main__.foo instance at 0x831934c>, <__main__.foo instance at > 0x83191cc>, <__main__.foo instance at 0x8311fac>, <__main__.foo > instance at 0x831932c>]) > > I want that f and f1, that have both self.a set to 1, look the same to > the set, so that it doesn't add f1. In this case the instances looks > all different, so it adds them all. > > I tried rewriting __hash__ and __cmp__ in the foo class, so that > __hash__ simply returns self.a and __cmp__ return self.a == other.a __cmp__ does rich comparisons and is supposed to return 0 for equality, -1 if the object is less than the other, and 1 if it's greater than the other. So, using == as its definition is broken as it returns just a boolean. You'd want cmp(self.a, other.a) if you were defining __cmp__. However, == obviously works fine for __eq__, hence why switching to __eq__ fixed your problem. Also, __hash__ should probably delegate and be defined as hash(self.a) rather than just self.a itself. > > I thought this would work, but I was wrong. > I had to rewrite __eq__ with the same code of __cmp__ > > Why it doesn't work with __cmp__ or __hash__ ? Probably on account of one of the above errors I explained. Cheers, Chris -- I wonder if there's a Mrs. FoRk... > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Socket Programming and Data transer 'advice'
On Mon, Nov 17, 2008 at 10:42 AM, Abah Joseph <[EMAIL PROTECTED]> wrote: > I am planning to develop School Database Management System that will run on > Windows, Linux and Mac. The application will be Server/Client and GUI based. Have you considered basing this off existing software for schools, like one of the programs listed on http://en.wikipedia.org/wiki/Learning_management_system ? > > Modules I intende to use are: Python socket module, wxPython for GUI, Open > GL for image processing , email and so on. > > This is my first real python project and I really want to test myself with > this application. Sounds like one hell of a project. Are you sure you aren't encountering the Second System Effect (http://en.wikipedia.org/wiki/Second-system_effect) despite this being only your first project? > > Some planned features is:- > > SERVER > Manage Client connections > Handling Student/User registration > Handling backup > will also act as IM server (that will allow users to chat sometime) Jabber a.k.a. XMPP (http://www.jabber.org/web/Main_Page) would probably be a good option for IM. > > CLIENT > Connect to sever > Act as IM client > Retrieve data from server. > > I will not be able to list all features. > > My Question is: > > What is the best database to use? (Flat file, cPickle, MySql, Sqlite,XML > etc) MySQL or Sqlite, probably the former. The other ones you list aren't really databases per se. > > Security to make sure data is safe Use some kind of encryption; I'd recommend using KeyCzar - http://www.keyczar.org/ > > How are binary data transferred from location x to y?, and during the > transferring what should happen if not fully transferred and assume power > goes off. Start all over again or continue? > > What is the secret behind transparent file transfer like the one in Yahoo IM > (I can see what i`m transferring to you, u as well). Don't really know what you mean by this. > > Audio streaming. IceCast might be a good starting point - http://www.icecast.org/ > > My intension here is to know what to do or read more and not asking you to > write code for me > > Just your advice. Good luck. Sounds like an ambitious project. Hope the pointers I gave help. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to deal with globals during refactoring classes into separate files.
On Tue, Nov 18, 2008 at 4:14 PM, r0g <[EMAIL PROTECTED]> wrote: > Hi There, > > I'm refactoring some old code that uses global variables and was > originally written in one big flat file with a view to nicening it up > and then extending it. The problem I have though is when I move the > various classes out to their own separate files and reimport them back > in they can't see the globals in the main program. Most of the globals > were just constants and so I have been able to factor them out but > there's one that's kind of pivotal that I still need, basically a list > of all the threads I have running, I don't see how I could get rid of > that. Example follows... > > The original with global variable and classes all in one file... > > dirty_global = "whatever" > class example(): > def print_message(self): >print "Sure, "+dirty_global > a = example() > a.print_message() > Sure, whatever > > > But when I put the class in its own file and then import it back in... > > > from example_class import example > dirty_global = "whatever" > a = example() > a.p() > NameError: global name 'dirty_global' is not defined > > > > I had thought declaring the variable using the global keyword at the top > of the file might make it a global 'proper' (as per the manual) or that > using it at the top of the class file might somehow allow the class to > see the variable in file it was called from but clearly my understanding > of python namespaces and scoping isn't quite there yet as neither of > these seem to make any difference. A `global` declaration at the module-level, while syntactically valid, doesn't do anything. It only really makes sense to use `global` in function bodies. And as Gabriel explained, Python has no program-wide global scope. Global scope is always module-specific. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > How can get my classes to see this 'dirty_global' variable again? > > Thanks, > > Roger. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception difference 2.4 ==> 2.5
On Tue, Nov 18, 2008 at 8:56 PM, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote: > I am having a strange problem and I can't seem to zero in on it. I am > also having trouble reducing it to a small enough snippet that I can > post here. I think that I am doing what the more complex script does > but none of my attempts fail. So, here is a description just in case > someone has seen something that smells like this and can suggest some > areas to do further poking. > > I have a class that subclasses xmlrpcserver.RequestHandler. It has a > method that takes a function name that it looks up with getattr. It > then calls the looked up method in this try/except block: > >try: >return server_method(pkt) >except Exception, failure: >syslog(LOG_WARNING, "%s, %s" % (Exception, failure)) >self.print_tb(sys.exc_info()) > >try: fault = self.faultConverter.errorToFault(failure) >except Exception, err: >syslog(LOG_ERR, "Error processing failure: %r" % err) >fault = xmlrpclib.Fault(8002, "Internal error") > >syslog(LOG_DEBUG, "Converted failure %r to fault %r (%r)" % > \ (failure, fault, failure)) > >if fault.faultCode < 1: >syslog(LOG_ERR, "Unconverted fault: %r" % failure) > >return fault > > This class is then subclassed by another class that adds the methods > that are to be looked up. Those methods may raise exceptions if there > are errors. > > Under Python 2.4 this works fine. If an exception is raised in the > looked up method it gets handled by this code just fine. Under 2.5, > however, the exception is not caught here. It's as if there was no > try/except here at all. What happens under Python 2.6? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > I'm not sure if I have left off some critical piece of information or > just littered this post with red herrings. I'm open to both > reasoned suggestions as well as wild speculation. > > -- > D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves > http://www.druid.net/darcy/| and a sheep voting on > +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Non blocking socket server and storage engine
On Wed, Nov 19, 2008 at 2:36 AM, kdeveloper <[EMAIL PROTECTED]> wrote: > Hello Pythonists, > > I am building a non blocking socket server for incomming UDP packets. > The server needs to run at least three threads: > 1. getting data and pushing to "some" storage (at the moment I use > queue), > 2. acknowledge the package received > 3. retrieve the information from the storage and insert it in DB. > > The problem I have is that when I use queue it stores more packets in > the queue than it actually receives. An example: sent 99 UDP packets > and queue stored 600-750 entries (?) Why? I have no idea. I have > impression that I still do not understand completely how does the > queue work in python. No, I believe rather you don't completely understand UDP. Quoting from Wikipedia (http://en.wikipedia.org/wiki/User_Datagram_Protocol): "UDP does not guarantee reliability or ordering in the way that TCP does. Datagrams may arrive out of order, ***appear duplicated***, or go missing without notice." I think that might at least partially account for your duplicate entries. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Another issue is that I want the server to run very rupidly. The > server needs to get at least 100 packets per second, and the same > amount of acknowledges has to be sent back. > > The questions are: > 1. What is the best storage engine for Python and multithreading > server? > 2. Can I use queue for such problem? > 3. How does actually queue work in Python? (I know how it should work > generally, but somehow it doesn't work as I expect) > > Any hints & helps? Would be very grateful > > Cheers > K > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception difference 2.4 ==> 2.5
On Wed, Nov 19, 2008 at 8:24 AM, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote: > On Tue, 18 Nov 2008 22:33:35 -0800 > "Chris Rebert" <[EMAIL PROTECTED]> wrote: >> What happens under Python 2.6? > > Interesting. I installed 2.6 and tried it. My unit test still failed > but for a different reason that I will have to investigate but the > exceptions were handled correctly. Does this suggest something to you? I would wildly guess that you might have encountered a bug in Python that was since fixed. Hard to be sure though. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves > http://www.druid.net/darcy/| and a sheep voting on > +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting fractional part from a float without using string operations
On Wed, Nov 19, 2008 at 10:01 PM, srinivasan srinivas <[EMAIL PROTECTED]> wrote: > Yes it works for most of the cases. But it doesn't for the following case: > str(abs(int(1234567.89)-1234567.89)) > '0.88999898' Since you really care about significant figures here, have you considered using decimal rather than float as, IIRC, it handles this correctly? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks, > Srini > > > - Original Message > From: Tino Wildenhain <[EMAIL PROTECTED]> > To: srinivasan srinivas <[EMAIL PROTECTED]> > Cc: Jeremiah Dodds <[EMAIL PROTECTED]>; python-list@python.org > Sent: Wednesday, 19 November, 2008 7:33:46 PM > Subject: Re: Getting fractional part from a float without using string > operations > > srinivasan srinivas wrote: >> Yes. But it didn't give only the expected decimals. >> For ex: >> >>> a = 1.23 >> >>> abs(int(a) -a) >> 0.22998 >> I would like to get the result '0.23' only. > > well, thats what get stored internally - there > is no way around it if you are using floating > point numbers: > 0.23 > 0.23001 > > but str() handles the rounding correctly: > print 0.23 > 0.23 > print abs(int(a) -a) > 0.23 > > See also http://en.wikipedia.org/wiki/Floating_point > for the problems with FP figures. > > Regards > Tino > > > > Get perfect Email ID for your Resume. Grab now > http://in.promos.yahoo.com/address > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Two functionaly identical functions -> different results ??!
On Wed, Nov 19, 2008 at 11:24 PM, Barak, Ron <[EMAIL PROTECTED]> wrote: > Hi Guys, > > I cannot see any difference between read1() and read2() below, and yet, one > is okay, the other give an exception. > > In the first run, read2() is executed, and as expected, the text file is > printed > > $ cat ./gzip_try.py > import gzip > > FILE = "text_file.txt" > > def read2(): > try: > fl = gzip.GzipFile(FILE, "r") > print fl.read() > except IOError: > fl = open(FILE, "r") > print fl.read() > > def read1(): > try: > fl = gzip.GzipFile(FILE, "r") > except IOError: > fl = open(FILE, "r") > > print fl.read() > > read2() > #read1() > > $ python ./gzip_try.py > abc > 123 > > In the second run, read1() is executed, and an "IOError: Not a gzipped file" > exception is thrown from the "print fl.read()" line of read1(). > This is baffling to me, as the try...except should have established that the > file is a text and not gzip file ! > > $ cat ./gzip_try.py > import gzip > > FILE = "text_file.txt" > > def read2(): > try: > fl = gzip.GzipFile(FILE, "r") > print fl.read() > except IOError: > fl = open(FILE, "r") > print fl.read() > > def read1(): > try: > fl = gzip.GzipFile(FILE, "r") > except IOError: > fl = open(FILE, "r") > > print fl.read() > > #read2() > read1() > > $ python ./gzip_try.py > Traceback (most recent call last): > File "./gzip_try.py", line 22, in > read1() > File "./gzip_try.py", line 19, in read1 > print fl.read() > File "c:\Python25\lib\gzip.py", line 220, in read > self._read(readsize) > File "c:\Python25\lib\gzip.py", line 263, in _read > self._read_gzip_header() > File "c:\Python25\lib\gzip.py", line 164, in _read_gzip_header > raise IOError, 'Not a gzipped file' > IOError: Not a gzipped file > > $ > > Can anyone explain why read1() throws an exception, while read2() behaves > correctly ? As I believe someone else pointed out recently in a extremely similar thread, GzipFile apparently doesn't check that the underlying file is actually in gzip format until the .read() call, hence why its placement affects where the exception is thrown and thus how it's handled. read2() has the .read() for the gzipped case within the `try`, so the exception, if it's going to get thrown, is thrown there and handled by the except. In contrast, read1() has the .read() call outside the `try` and so the possible exception doesn't get caught. IOW, putting the GzipFile() creation in a `try` is pointless in this case as .read(), and not the initialization, throws the exception. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks, > Ron. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Using eval, or something like it...
On Thu, Nov 20, 2008 at 3:54 PM, r0g <[EMAIL PROTECTED]> wrote: > Scott David Daniels wrote: >> r0g wrote: >>> John Machin wrote: You mention "variables of a class" but you then proceed to poke at an instance of the class Check out setattr (and getattr) in the docs. >>> The former i.e. the variables of an instance of a class. Thanks :-) >> >> Careful here. Your wording seems to indicate you misunderstand the >> Python model. The instance doesn't have variables (and your class built >> nothing that could be called an instance variable). Think of the >> attributes of an instance (or a class) as "values attached to (or >> associated with) the instance." If you don't you are setting yourself >> up to discover a pile of bugs that you don't understand. >> >> --Scott David Daniels >> [EMAIL PROTECTED] > > > OK now I'm confused, let me explain how I see things at the moment and > you can correct me... > > A class is like a template which combines a complex data type (made from > a combination of other data types) and the methods that operate on that > data type. > > You generally don't work with classes directly but you make instances of > them, each instance has it's own internal state and methods, initially > these are the same as the templates but can be changed or overridden > without affecting the state of any other instances you might have. > > While the perceived wisdom is that you should encapsulate all the > methods you need to modify your classes' state within the class itself > Python does (for better or worse) permit you to reach inside a class and > futz with it's state directly from outside. > > The bits of an instance's state one might futz with (from within or > without) i.e. the primitives that make up the complex object the class > is a representation of, I think of as it's variables. > > It would seem from this setattr function that the proper term for these > is 'attributes'. That for many years I have considered pretty much any > named thing that may vary a 'variable' might be at the root of the > problem here as it's a very un-specific term... > > So I gather you are saying that the fragments of state within a class Within an instance > are so distinct from ordinary common or garden variables that it is > incorrect to think of them, or describe them, as variables, much like > quarks should not really be regarded as distinct particles, and they > should only be thought of and described as 'attributes' to avoid confusion? > > Is this correct enough for me to avoid the aforementioned bug pile? Yes, I think so. > > Also then, what _is_ an "instance variable" ? Metasyntatic variables: C - some class x - some instance y - the "word" after the dot in the expression: x.y My working definitions based on my knowledge of Python: Attribute - y is an attribute of x. Includes instance variables, properties, and dynamically generated attributes. Since x.y really ends up doing x.__getattribute__("y") behind the scenes, overriding __getattribute__ lets you make attribute lookup more dynamic and have it do interesting things. For example, you could write a class overriding __getattribute__ so that x.y (for any valid Python name y) opened a file with the name y and returned a file object for this file (i.e. x.z returns file("z","w"), x.q returns file("q","w"), etc without enumerating "q", "z", etc anywhere in the class). Instance variable - In `x.y`, y is an instance variable of x if it's stored in x.__dict__ or x.__slots__, it's not a method of x (though it can be a function), and it's not a property. Property - y is a property if x.y causes a method call and returns the result of said method call. Basically, x.y becomes equivalent to x.z() if y is a property. Properties can also allow `x.y = a` to be equivalent to `x.z(a)` and `del x.y` to be equivalent to `x.z()`. Properties are created using the built-in function property() Class variable - Unless you're using metaclasses, in C.y, y is always a class variable of C. Thus, methods are technically also class variables. Using metaclasses, C is both a class itself and an instance of another class D, in which case the definition of "instance variable" (interpreted with regards to C being an instance of D) applies to whether y is a class variable of C or not. Class method - Created using the built-in function classmethod() Essentially, attribute lookup is very dynamic in Python, which complicates things a good bit, so the only thing we know for sure about x.y is that y is an attribute of x. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks, > > > Roger. > > Q: How many pedants does it take to change a lightbulb? > A: Well actually you mean "replace" a lightbulb. > Q: Have you ever kissed a girl? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending username password to a webpage
On Thu, Nov 20, 2008 at 7:52 PM, KDawg44 <[EMAIL PROTECTED]> wrote: > Hi, > > Is there a way to essentially simulate populating a text box and > calling a submit button on a webpage? I want to write an app that > gets a users information from a website and then uses that to get > information from another site. The first site requires a log in. There's the mechanize library for programmatic web browsing: http://wwwsearch.sourceforge.net/mechanize/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks for any advice that gets me in the right direction. > > Thanks. > > Kevin > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional parameter object re-used when instantiating multiple objects
On Thu, Nov 20, 2008 at 9:26 PM, alex23 <[EMAIL PROTECTED]> wrote: > On Nov 21, 10:07 am, Aaron Brady <[EMAIL PROTECTED]> wrote: >> Why, I would expect the interpreter to define the functions when it >> first hits the def, that is, at the point of definition. > > Then why are you arguing that the parameters should be re-defined at > the point of calling? I would assume because using the "def is start of definition" theory, anything after the "def" is part of the function definition/body and should not be immediately executed, but rather be executed at call-time. The function body comes after the "def" and doesn't get run immediately, so neither should the default argument values. I take no position on the virtue of said theory. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: initialization in argument definitions
On Fri, Nov 21, 2008 at 1:25 PM, Brentt <[EMAIL PROTECTED]> wrote: > Hi, I know this is a terribly simple question, but the docs seem to be > designed for people who probably find a the answer to this question > terribly obvious. But its not at all obvious to me. > > I can't figure out why when I define a function, a variable > (specifically a list) that I define and initialize in the argument > definitions, will not initialize itself every time its called. So for > example, when making a simple list of a counting sequence from num (a > range list), if I call the function multiple times, it appends the > elements to the list generated the times it was called before, even > though the variable for the list is initialized in the argument > definitions. > > def foo_range(num,aList = []): That should probably be: def foo_range(num, aList=None): > aList = [] > #why is this seemingly extra initialization necessary? shouldn't it be > initialized in the argument definitions? > #but if its not there and the function is called multiple times the > elements generated (see below) > #append to the list generated before. > while num <= 10: > aList.append(num) > num +=1 > else: > return aList > > Why is this? Thanks, hope its not a stupid quesiton. No, but it is a very frequently asked one: http://effbot.org/zone/default-values.htm Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: I cannot open images in g-mail
This mailinglist is about the Python programming language, not Gmail; thus, your question is completely irrelevant. I would suggest you ask your question in http://groups.google.com/group/Gmail-Help-Discussion instead. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com On Sun, Nov 23, 2008 at 6:52 AM, <[EMAIL PROTECTED]> wrote: > I use windows vista home premium. Whenever I open an incoming message > in my inbox, no images are shown. Also, the option to display all > images does not appear at the top of the message. The only option > shown is "display images below". When I click that option, nothing > happens. I am guessing i must have something set up incorrectly on my > laptop. Can anyone help me with this problem. I',m pretty confused > right now. Any input would be appreciated. Thanks. > Fred > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Quick question about None and comparisons
On Mon, Nov 24, 2008 at 5:52 PM, Giampaolo Rodola' <[EMAIL PROTECTED]> wrote: > Sorry for the title but I didn't find anything more appropriate. > To have a less verbose code would it be ok doing: > > if a > b: > > ...instead of: > > if a is not None and a > b: > > ...? > Is there any hidden complication behind that? Yes. In Python 3.0, doing non-equality comparisons with None will raise a TypeError because it's nonsensical to ask whether two objects of unrelated types are less than or greater than each other (e.g Is [1,2] > "ab" ?). Assuming `a` will never take on a value considered boolean false, you can do `if a and a > b:` instead. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > Thanks in advance > > --- Giampaolo > code.google.com/p/pyftpdlib/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Reg Expression - Get position of >
On Tue, Nov 25, 2008 at 8:36 AM, M_H <[EMAIL PROTECTED]> wrote: > > Hey, > > I need the position of the last char > > > Let's say I have a string > mystr =
Re: checking for mis-spelled variable names / function names
On Tue, Nov 25, 2008 at 3:16 PM, News123 <[EMAIL PROTECTED]> wrote: > Hi, > > Let's imagine following code > > def specialfunc(): >print "very special function" > > name= getuserinput() > if name == 'one_name_out_of_a_million': >print "Hey your name '%s' is really rare" % namee >specialfunk() > > my python script could survive thousands of runs before falling into > the mis-spelled code section. ('namee' instead of 'name' and > 'specialfunck()' instead of 'specialfunc()' > I know that good designers should always test their code and have > complete code coverage, before releasing their beasts into the wild, but > in my experience this is not always what happens. > > I fell already over quite of my own sins, but also over typoes of other > python authors. > > Is there any way in python to check for mis-spelled variable / function > names? > > > In perl for example 'use strict;' would detect bad variable names, > though it wouldn't detect calls to undeclared functions. > > I am aware, that there is absolutely valid (and useful) python code with > undefined functions / variable names. > > However for the scripts that I write I would prefer to identify as many > typoes as possibe already when trying to run the script the first (and > not the millionth) time. > > Do you have ideas suggestions? > Are there any 'lint' like tools trying to analyze python code for > potential stupidities? PyLint: http://www.logilab.org/857 PyChecker: http://pychecker.sourceforge.net/ I believe they both check for variable name typos, among many other things. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > If yes, what would be 'the' way to add these tools / modules at )least > during the development cycle) to the scripts. > > > thanks in advance for any thoughts / suggestions. > > > bye > > > N > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Reg Expression - Get position of >
On Wed, Nov 26, 2008 at 1:48 AM, M_H <[EMAIL PROTECTED]> wrote: > On Nov 25, 11:06 pm, r <[EMAIL PROTECTED]> wrote: >> On Nov 25, 4:33 pm, Jorgen Grahn <[EMAIL PROTECTED]> wrote: >> >> >> >> > On Tue, 25 Nov 2008 12:41:53 -0800 (PST), r <[EMAIL PROTECTED]> wrote: >> > > On Nov 25, 10:36 am, M_H <[EMAIL PROTECTED]> wrote: >> > >> Hey, >> >> > >> I need the position of the last char > >> >> > >> Let's say I have a string >> > >> mystr =
Re: import in a class
On Wed, Nov 26, 2008 at 9:30 AM, TP <[EMAIL PROTECTED]> wrote: > Hi everybody, > > Here is a file "test_import_scope.py": > ## > class a(): > import re > def __init__( self ): > if re.search( "to", "toto" ): > self.se = "ok!" > def print_se( self ): > print self.se > a().print_se() > ## > > When python executes this file, we obtain an error: > > $ python test_import_scope.py > [...] > NameError: global name 're' is not defined > > Why? Because Python doesn't look in class-scope when doing name resolution. It checks the local [function] namespace, then any nested [function] scopes (not applicable in this case), then the module/global namespace, and finally the builtins namespace. The class' namespace never comes into the equation. Consider this simpler example (remember that `import` assigns a module to its name in the importing scope): >>> class Foo(object): ... A=1 ... def foo(self): print A ... >>> Foo().foo() Traceback (most recent call last): File "", line 1, in File "", line 3, in foo NameError: global name 'A' is not defined So in foo(), `A` can be accessed by Foo.A or self.A, but not just plain `A`. I agree it's not entirely intuitive, but remember that Python != Java. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > When the re module is imported in the __init__ function or out of the class > (at the top of the file), it works obviously perfectly. > > Thanks in advance, > > Julien > > -- > python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z > (55l4('])" > > "When a distinguished but elderly scientist states that something is > possible, he is almost certainly right. When he states that something is > impossible, he is very probably wrong." (first law of AC Clarke) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: best IDE
On Wed, Nov 26, 2008 at 9:59 AM, asit <[EMAIL PROTECTED]> wrote: > Which one is the best IDE for python This was recently discussed. To avoid needlessly rehashing said discussion, see the thread at http://groups.google.com/group/comp.lang.python/browse_thread/thread/7fd136aef1c63e47/fbaff90068f0fe02 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it possible (and wise) to extend the None-type ?
On Wed, Nov 26, 2008 at 9:55 AM, Stef Mientki <[EMAIL PROTECTED]> wrote: > hello, > > I've the idea that I always have a lot of useless code in my programs, > like the next example. > > def _On_Menu_File_Open ( self, event = None ): > if event : >event.Skip () > > instead of > > def _On_Menu_File_Open ( self, event = None ): > event.Skip () > > So I would like to extend the None-type (if that's possible), It's not. You can't graft new methods onto NoneType (a.k.a. type(None)), and you can't subclass NoneType either. You might be interested in the recipe for a "Null" type: http://code.activestate.com/recipes/68205/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > with a dummy Skip() method. > > Is it wise to do ? > If not what are the disadvantages ? > > thanks, > Stef Mientki > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
On Wed, Nov 26, 2008 at 11:11 AM, Nan <[EMAIL PROTECTED]> wrote: > Hello, > I just started to use Python. I wrote the following code and > expected 'main' would be called. > > def main(): > print "hello" > > main > > But I was wrong. I have to use 'main()' to invoke main. The python > interpreter does not give any warnings for the above code. Is there > any way/tool to easily detect this kind of errors ? Python has first-class functions, so you can pass a function to another function (so the line `main` has a meaning, just not a useful one). Also, Python doesn't do compile-time typechecking, so it has no way of knowing that `main` is a function and not a plain variable until runtime. Thus, the parentheses are required for a function call even when there are no arguments. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks ! > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python equivalent of Common Lisp Macros?
On Wed, Nov 26, 2008 at 11:13 AM, dpapathanasiou <[EMAIL PROTECTED]> wrote: > I'm using the feedparser library to extract data from rss feed items. > > After I wrote this function, which returns a list of item titles, I > noticed that most item attributes would be retrieved the same way, > i.e., the function would look exactly the same, except for the single > data.append line inside the for loop. > > In CL, I could simply write a macro, then replace the data.append line > depending on which attribute I wanted. > > Is there anything similar in Python? Yes, use higher-order functions. See below. > > Here's the function: > > def item_titles (feed_url): Replace previous line with: def item_titles(feed_url, attr_getter): >"""Return a list of the item titles found in this feed url""" >data = [] >feed = feedparser.parse(feed_url) >if feed: >if len(feed.version) > 0: >for e in feed.entries: >data.append(e.title.encode('utf-8')) Replace previous line with: data.append(attr_getter(e)) >return data Example usage: def title_getter(entry): return entry.title.encode('utf-8') titles = item_titles("some feed url here", title_getter) As I'm not familiar with feedparser, you might want to move where the .encode() takes place, but you get the idea. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: help with class
On Wed, Nov 26, 2008 at 5:21 PM, tekion <[EMAIL PROTECTED]> wrote: > Hi, > so I am assuming global name space refers to the location of where the > module is imported, for example my previous example where I call the > gzip module from test_class class, like so: > > class test_class: > import gzip > > did not work because of scoping. So global name space in this case is > declaring the import outside of test_class like so: > > import gzip > class test_class: > etc.. > > Is my assumption correct? Thanks. Yes. Global == module-level. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to construct a list of only one tuple
On Thu, Nov 27, 2008 at 2:39 PM, TP <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > >>> >>> a=("1","2") >>> >>> b=[("3","4"),("5","6")] >>> >>> list(a)+b >>> ['1', '2', ('3', '4'), ('5', '6')] >> > a = ("1", "2") > b = [("3", "4"), ("5", "6")] > [a] + b >> [('1', '2'), ('3', '4'), ('5', '6')] > > Thanks a lot. > Why this difference of behavior between list(a) and [a]? Because list() is used to convert other iterable types into lists (e.g. list("abc") ==> ['a','b','c'], list((c,d)) ==> [c,d], list(set(x,y,z)) ==> [y, z, x]). In contrast, a list literal just constructs a list. This makes sense because the behavior of list() is useful and you can just use the literal syntax instead for cases such as yours. In Python 3.0, I believe you'll be able to use the splat operator to do e.g. [a, *b] to get your desired result. For reference: list(a) <==> [x for x in a] [a,b,c] <==> list((a,b,c)) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Julien > > -- > python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z > (55l4('])" > > "When a distinguished but elderly scientist states that something is > possible, he is almost certainly right. When he states that something is > impossible, he is very probably wrong." (first law of AC Clarke) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with capturing error
On Thu, Nov 27, 2008 at 12:33 PM, tekion <[EMAIL PROTECTED]> wrote: > Hello, > I am getting the following error and my script is bailing out because > of it. I have tried capturing it but it does not seem to work. Below > is the error: > > ValueError: I/O operation on closed file > > > the above error is received when, the following code snippet is > executed: >try: >117 self.xml_file.close() >118 except ValueError: >119 print "file, %s is already closed" % self.seek_file > > Any idea why line 118, is not capturing the error? Thanks. In order to help you debug an exception, generally a full Traceback is necessary. If you post the full traceback, it will help people immensely in helping determine the cause of your problem. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP!...Google SketchUp needs a Python API
On Thu, Nov 27, 2008 at 3:18 PM, r <[EMAIL PROTECTED]> wrote: > Hello fellow Python Advocates! > Help me promote Python to a larger audience. > > An introduction to SketchUp: > > I don't know if you are familiar with "Google Sketchup". It is the > best 3d CAM program available. > > Credit where credit is do: > == > You know, Guidio van Rossum really nailed it when he created this > language. He took the best of everything he saw that was good and left > out everything he saw was bad (i think only one other entity has done > his before long ago...see Book of Genesis ;) > > Now if we could get Python into SketchUp this would be a win for > SketchUp, AND for Python. > Python would get more exposure, and SketchUP would be easier to use, > sticking to there policy above. And when people have a choice between > Python and Ruby... you and I both know who will win that > competition ;-). > > Now before you say..."don't tell us, tell the SketchUp DEV TEAM". I > have hinted at adding Python as a second scripting API, but what needs > to happen is to get a list together of people that use SketchUp or > people who want use SketchUp, or people who just think it is a damn > good idea and submit it to the DEV TEAM. > > Look forward to hearing from you! I am open to any suggestions good or > bad. I don't really give a care about SketchUp, but just FYI, you are aware that Guido van Rossum and some other prominent Pythonistas are currently employed by Google, right? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating classes and objects more than once?
On Thu, Nov 27, 2008 at 2:36 PM, Viktor Kerkez <[EMAIL PROTECTED]> wrote: > A better way to do this was http://pastebin.com/m1130d1fe :) > -- > http://mail.python.org/mailman/listinfo/python-list > The Python position on singletons is generally to just use a module instead (preferred), or apply the Borg pattern: http://code.activestate.com/recipes/66531/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP!...Google SketchUp needs a Python API
On Thu, Nov 27, 2008 at 3:33 PM, r <[EMAIL PROTECTED]> wrote: > On Nov 27, 5:27 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote: >> On Thu, Nov 27, 2008 at 3:18 PM, r <[EMAIL PROTECTED]> wrote: >> > Hello fellow Python Advocates! >> > Help me promote Python to a larger audience. >> >> > An introduction to SketchUp: >> > >> > I don't know if you are familiar with "Google Sketchup". It is the >> > best 3d CAM program available. >> >> >> > Credit where credit is do: >> > == >> > You know, Guidio van Rossum really nailed it when he created this >> > language. He took the best of everything he saw that was good and left >> > out everything he saw was bad (i think only one other entity has done >> > his before long ago...see Book of Genesis ;) >> >> > Now if we could get Python into SketchUp this would be a win for >> > SketchUp, AND for Python. >> > Python would get more exposure, and SketchUP would be easier to use, >> > sticking to there policy above. And when people have a choice between >> > Python and Ruby... you and I both know who will win that >> > competition ;-). >> >> > Now before you say..."don't tell us, tell the SketchUp DEV TEAM". I >> > have hinted at adding Python as a second scripting API, but what needs >> > to happen is to get a list together of people that use SketchUp or >> > people who want use SketchUp, or people who just think it is a damn >> > good idea and submit it to the DEV TEAM. >> >> > Look forward to hearing from you! I am open to any suggestions good or >> > bad. >> >> I don't really give a care about SketchUp, but just FYI, you are aware >> that Guido van Rossum and some other prominent Pythonistas are >> currently employed by Google, right? >> >> Cheers, >> Chris >> -- >> Follow the path of the Iguana...http://rebertia.com >> >> > Thanks >> > -- >> >http://mail.python.org/mailman/listinfo/python-list > > Of course, but you are not suggesting that i bother Guido with this. I > am sure he is too busy. No, obviously that was not my implication. - Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP!...Google SketchUp needs a Python API
On Fri, Nov 28, 2008 at 9:52 AM, r <[EMAIL PROTECTED]> wrote: >> and we're not throwing ourselves at your pet project because most of us >> don't give a monkey's toss about Sketchup. > Why should we put our time and >> energy into a piece of software that we don't care about? > > AGAIN, I'm NOT asking you to support SKETCHUP I am asking for support > for PYTHON! Did you even read my entire OP?? Or did you just jump on > Chris's bandwagon? Do you think for yourself, or do you follow blindly > like a SHEEPLE?? > Since when do I have a bandwagon? I made one purely informational post and just said that I personally didn't really care one way or another about SketchUp. I'm not particularly pro- or anti- your idea, I just classified it as "personally irrelevant" but thought I'd point out one possibly relevant fact to you to be helpful. That's all. There Is No Cabal. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP!...Google SketchUp needs a Python API
On Thu, Nov 27, 2008 at 4:09 PM, r <[EMAIL PROTECTED]> wrote: > On Nov 27, 5:42 pm, r <[EMAIL PROTECTED]> wrote: >> On Nov 27, 5:38 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote: >> > On Thu, Nov 27, 2008 at 3:33 PM, r <[EMAIL PROTECTED]> wrote: >> > > On Nov 27, 5:27 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote: >> > >> On Thu, Nov 27, 2008 at 3:18 PM, r <[EMAIL PROTECTED]> wrote: >> > >> > Hello fellow Python Advocates! >> > >> > Help me promote Python to a larger audience. >> >> > >> > An introduction to SketchUp: >> > >> > >> > >> > I don't know if you are familiar with "Google Sketchup". It is the >> > >> > best 3d CAM program available. >> > >> >> >> > >> > Credit where credit is do: >> > >> > == >> > >> > You know, Guidio van Rossum really nailed it when he created this >> > >> > language. He took the best of everything he saw that was good and left >> > >> > out everything he saw was bad (i think only one other entity has done >> > >> > his before long ago...see Book of Genesis ;) >> >> > >> > Now if we could get Python into SketchUp this would be a win for >> > >> > SketchUp, AND for Python. >> > >> > Python would get more exposure, and SketchUP would be easier to use, >> > >> > sticking to there policy above. And when people have a choice between >> > >> > Python and Ruby... you and I both know who will win that >> > >> > competition ;-). >> >> > >> > Now before you say..."don't tell us, tell the SketchUp DEV TEAM". I >> > >> > have hinted at adding Python as a second scripting API, but what needs >> > >> > to happen is to get a list together of people that use SketchUp or >> > >> > people who want use SketchUp, or people who just think it is a damn >> > >> > good idea and submit it to the DEV TEAM. >> >> > >> > Look forward to hearing from you! I am open to any suggestions good or >> > >> > bad. >> >> > >> I don't really give a care about SketchUp, but just FYI, you are aware >> > >> that Guido van Rossum and some other prominent Pythonistas are >> > >> currently employed by Google, right? >> >> > >> Cheers, >> > >> Chris >> > >> -- >> > >> Follow the path of the Iguana...http://rebertia.com >> >> > >> > Thanks >> > >> > -- >> > >> >http://mail.python.org/mailman/listinfo/python-list >> >> > > Of course, but you are not suggesting that i bother Guido with this. I >> > > am sure he is too busy. >> >> > No, obviously that was not my implication. >> > - Chris >> >> > -- >> > Follow the path of the Iguana...http://rebertia.com >> >> Are you against promoting python? > > To merely say... "Well Guido and some high level Python people work at > Google and if Python is not in SketchUp now it will never be"... is > pretty self defeating to me. Weather you like SketchUp or not doesn't You're putting words in my mouth. My intention was more, "Hey, there are some prominent Python people working for Google. That should probably help your cause.". However, given how the thread has evolved so far, that now looks less than likely. On the bright side, at least the scripting interface isn't in Java, right? Cheers, Chris > matter. This is a call for a grass roots movement to further the > incorporation of Python into a popular and useful app. I'm not asking > for people to support SketchUp here...I am asking people to support > Python. Of all Places in the world, there should be support here. I > hope at least you care about Python. > > Sure this may blow under the rug but hey...doesn't hurt to try. My > call was a "testing the waters" to see if there if fact are any Python- > SketchUp fans here. Maybe your a Ruby fan, i don't know, but that > would explain your quick disposal of the idea though. > -food for thought- > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Library to display detail hardware information
On Fri, Nov 28, 2008 at 7:51 AM, Hanny Wibisono <[EMAIL PROTECTED]> wrote: > Is there any python library that display very detailed hardware information > and it must run in linux environtment ? It's not Python, but you could run it using the `subprocess` module from Python: http://ezix.org/project/wiki/HardwareLiSter Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Beautiful soup tag attributes - Dictionary?
On Sun, Nov 30, 2008 at 8:51 PM, killsto <[EMAIL PROTECTED]> wrote: > The documentation says I can find attributes of tags by using it as a > dictionary. Ex: > > product = p.findAll('dd') .findAll() produces a *list* of tags The example in the docs is: firstPTag, secondPTag = soup.findAll('p') which is using *tuple unpacking*, so it's equivalent to: tags = soup.findAll('p') firstPTag = tags[0] #slicing the list to get individual item secondPTag = tags[1] So, you either need to use .find() instead of .findAll(), or treat the result of .findAll() correctly as a list of tags. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > print product['id'] > > However, when I try that python thinks I am slicing it. When I print > product, it works but is a list. I am pretty sure I have the latest > version. > > Any ideas? > > Reference: > http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python introspection and namespace weird question
On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana <[EMAIL PROTECTED]> wrote: > Hello everybody, > > Is there an easy way to do something like this in python ? > red_car = MyVehicleClass() car = red_car car.labels() > ['red_car' , 'car' ] > > In other words, does an instance has access to its name pointers ? In short, No. (Cue another debate over whether Python uses call-by-X semantics...) Typically people who want to do such things actually want/should use a dictionary mapping string keys to instance values instead. Note that in certain limited cases, voodoo involving the locals() or globals() built-in functions or the `inspect` module can work, but not in the common general case. But generally these techniques are considered bad style and kludgey unless you're writing a debugger or something equally meta, with using a dictionary as explained previously being much preferred. For example, for your particular code above, the following happens to work: [name for name, obj in locals().iteritems() if obj is car] #==> ['red_car' , 'car' ] But this will only give the names in the current function of the particular car object. Likewise, globals() works only for module-level names, and the `inspect` module's magic only works for names in calling functions (i.e. those below the current one in the callstack). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance, > > Rayene > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it safe to modify the dict returned by vars() or locals()
On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch <[EMAIL PROTECTED]> wrote: > Hi, > > I am looking for an elegant way to solve the following problem: > > Within a function > > def Foo(**parms) > > I have a list of names, say VList=['A','B','C1'] > and I like to generate abbreviation > _A identical to parms['A'] Could you explain what you mean by that? Your sample code doesn't seem to do any "abbreviation"... Otherwise I don't see why you don't just have a proper parameter list. > > for that I could write > > def Foo(**parms) : > for N in VList : >if N in parms : > vars()[N]= parms[N] >else : > vars()[N]= None > > Does this work, is it typical Python? >From the docs (http://docs.python.org/library/functions.html): locals() Update and return a dictionary representing the current local symbol table. *Warning*: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. Free variables are returned by locals() when it is called in a function block. Modifications of free variables may not affect the values used by the interpreter. Free variables are not returned in class blocks. As the warning states, it modifying the dict doesn't really work (except at the module level, but that's an implementation detail IIRC) For example: >>> def foo(): ... a = 3 ... l = locals() ... l['a'] = 5 ... print a ... >>> foo() 3 In any case, it'd be considered a bit of a hack. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Many thanks for a hint, > Helmut. > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't doc has predifined name and location ?
On Mon, Dec 1, 2008 at 1:22 PM, Stef Mientki <[EMAIL PROTECTED]> wrote: > hello, > > I'm very satisfied about the great standardization of doc strings in python. > Now in contrast to that, > the general documentation of libraries, > either in plain text, html, pdf, chm, ... > doesn't have a standarized name nor location. > > Why is that ? I suppose the need for such standardization has just never arisen. Googling for docs, checking the library's website, or doing `locate library-name-here | grep doc` in bash seems to work well enough for people that no one has found it necessary to pursue the creation of such a standard. Sidenote: what Python projects publish their docs in CHM besides possibly Win32 GUI programs? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python introspection and namespace weird question
On Mon, Dec 1, 2008 at 12:23 PM, Rayene Ben Rayana <[EMAIL PROTECTED]> wrote: > Thanks Chris, > > Yeah it is kinda meta thing. My app allows to create a scene (a set of GUI > objects). A scene can be saved as a python script. And, it can be loaded > again using execfile(). > > each GUI object has a label. So, in the script scene, declaring an object in > a scene file should look like this: > > red_car = MyVehicleClass(label = 'red_car') > > But, I wanted to simplify the syntax of scene files and avoid repetition so > it would look like > > red_car = MyVehicleClass() > > with the label attribute automatically set to the name of the corresponding > variable. > I tried your locals().iteritems tip and it works perfectly. > > The question now is: Given what I just explained, do you still think it is > bad programming to do that ? Should I better use the first syntax ? Assuming the object declarations are all at the module-level and you have some rule for dealing with objects with multiple "names", using the trick I outlined but with globals() instead of locals() seems reasonable, albeit a bit of a hack, but since this is just a script, that seems acceptable. IMHO, it's an OK trade-off in order to comply with the DRY (Don't Repeat Yourself) principle in this case. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Cheers, > > Rayene, > > I want to use that to simplify the syntax of the > > On Mon, Dec 1, 2008 at 7:37 PM, Chris Rebert <[EMAIL PROTECTED]> wrote: >> >> On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana >> <[EMAIL PROTECTED]> wrote: >> > Hello everybody, >> > >> > Is there an easy way to do something like this in python ? >> > >> >>>> red_car = MyVehicleClass() >> >>>> car = red_car >> >>>> car.labels() >> > ['red_car' , 'car' ] >> > >> > In other words, does an instance has access to its name pointers ? >> >> In short, No. (Cue another debate over whether Python uses call-by-X >> semantics...) >> >> Typically people who want to do such things actually want/should use a >> dictionary mapping string keys to instance values instead. >> >> Note that in certain limited cases, voodoo involving the locals() or >> globals() built-in functions or the `inspect` module can work, but not >> in the common general case. But generally these techniques are >> considered bad style and kludgey unless you're writing a debugger or >> something equally meta, with using a dictionary as explained >> previously being much preferred. >> >> For example, for your particular code above, the following happens to >> work: >> [name for name, obj in locals().iteritems() if obj is car] #==> >> ['red_car' , 'car' ] >> >> But this will only give the names in the current function of the >> particular car object. Likewise, globals() works only for module-level >> names, and the `inspect` module's magic only works for names in >> calling functions (i.e. those below the current one in the callstack). >> >> Cheers, >> Chris >> -- >> Follow the path of the Iguana... >> http://rebertia.com >> >> > >> > Thanks in advance, >> > >> > Rayene >> > >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > >> > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to sort a list of file paths
On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John <[EMAIL PROTECTED]> wrote: > Hi, > > > > This weekend I had some problems to get a list containing file paths to be > sorted in a way that I could use. > > > > I also found a thread in this mailing list ( > http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and > realized that others might be interested in a solution. > > > > So... here is my five cents regarding file path sorting: > > > > Problem description: > > > > You have a list containing some file names: > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > > > If you sort this list in the conventional way you end up with a result like: > > > file_list.sort() > print file_list > > ['File1.txt','File10.txt','File2.txt'] > > > > Solution: > > > > Sort the list by splitting alphas and digits in to groups and compare them > separately. > > > > import re > > def true_alphanum_cmp(a,b): > > aa = re.findall(r'\d |\D ', a) > > bb = re.findall(r'\d |\D ', b) > > for i in range(min(len(aa),len(bb))): > > if aa[i].isdigit() and bb[i].isdigit(): > > c = cmp(int(aa[i]),int(bb[i])) > > else: > > c = cmp(aa[i],bb[i]) > > if c!=0: > > return c > > return cmp(len(aa),len(bb)) > > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > file_list.sort(true_alphanum_cmp) > > > > If the formatting in this mail is messed up you can find the example at > http://arainyday.se/notebook/true_alphanum_cmp.php > > > > All comments and improvements are welcome! Sounds like the issue discussed in the post on Coding Horror: http://www.codinghorror.com/blog/archives/001018.html It even links to another Python version of the algorithm. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Best regards > > John Eriksson > > _ > > > > Logica - Releasing your potential > > Tegsplan 2b > > 904 20 UMEÅ > > Sweden > > > > T: +46 (0) 90 15 91 38 > > M: +46 (0) 70 366 16 77 > > E: [EMAIL PROTECTED] > > www.logica.se > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple ini Config parser examples needed
On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN <[EMAIL PROTECTED]> wrote: > Hello, > > I have a very simple ini file that I needs parsed. What is the best way I > can parse an ini file that doesn't include sections? > > As in: > Since it appears that ConfigParser requires at least one section header, I'll assume the file starts with the following line: [main] > person=tall > height=small > shoes=big > > > Thats it. Can anyone help me? Completely untested: import ConfigParser config = ConfigParser.RawConfigParser() config.readfp(open("path/to/file.cfg")) config.get("main", "height") #==> "small" Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks, > Ron > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple ini Config parser examples needed
On Tue, Dec 2, 2008 at 2:51 PM, Glenn Linderman <[EMAIL PROTECTED]> wrote: > On approximately 12/2/2008 1:31 PM, came the following characters from the > keyboard of Chris Rebert: >> >> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN <[EMAIL PROTECTED]> >> wrote: >> >>> >>> Hello, >>> >>> I have a very simple ini file that I needs parsed. What is the best way >>> I >>> can parse an ini file that doesn't include sections? *Bangs head against wall repeatedly* I merely glossed the question and missed that all-important second sentence! fsck! My apologies, I shouldn't write email before having coffee :) Fortunately Tim followed quickly with the correct answer to the OP. - Chris >>> >>> As in: >>> >>> >> >> Since it appears that ConfigParser requires at least one section >> header, I'll assume the file starts with the following line: >> >> [main] >> >>> >>> person=tall >>> height=small >>> shoes=big >>> >>> >>> Thats it. Can anyone help me? >>> >> >> Completely untested: >> >> import ConfigParser >> config = ConfigParser.RawConfigParser() >> config.readfp(open("path/to/file.cfg")) >> config.get("main", "height") #==> "small" >> >> Cheers, >> Chris >> > > Of course the OP question was that the line you assume isn't there. But if > the ini is simple, maybe it is short enough to read into a string, then > prepend the line, then parse with ConfigParser. > > -- > Glenn -- http://nevcal.com/ > === > A protocol is complete when there is nothing left to remove. > -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking > > -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 3.0 final
On Wed, Dec 3, 2008 at 7:47 PM, Daniel Fetchinson <[EMAIL PROTECTED]> wrote: >> On behalf of the Python development team and the Python community, I >> am happy to announce the release of Python 3.0 final. >> >> Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major >> milestone in Python's history, and was nearly three years in the >> making. This is a new version of the language that is incompatible >> with the 2.x line of releases, while remaining true to BDFL Guido van >> Rossum's vision. Some things you will notice include: >> >> * Fixes to many old language warts >> * Removal of long deprecated features and redundant syntax >> * Improvements in, and a reorganization of, the standard library >> * Changes to the details of how built-in objects like strings and >> dicts work >> * ...and many more new features >> >> While these changes were made without concern for backward >> compatibility, Python 3.0 still remains very much "Pythonic". >> >> We are confident that Python 3.0 is of the same high quality as our >> previous releases, such as the recently announced Python 2.6. We will >> continue to support and develop both Python 3 and Python 2 for the >> foreseeable future, and you can safely choose either version (or both) >> to use in your projects. Which you choose depends on your own needs >> and the availability of third-party packages that you depend on. Some >> other things to consider: >> >> * Python 3 has a single Unicode string type; there are no more 8-bit >> strings >> * The C API has changed considerably in Python 3.0 and third-party >> extension modules you rely on may not yet be ported >> * Tools are available in both Python 2.6 and 3.0 to help you migrate >> your code >> * Python 2.6 is backward compatible with earlier Python 2.x releases >> >> We encourage you to participate in Python 3.0's development process by >> joining its mailing list: >> >> http://mail.python.org/mailman/listinfo/python-3000 >> >> If you find things in Python 3.0 that are broken or incorrect, please >> submit bug reports at: >> >> http://bugs.python.org/ >> >> For more information, links to documentation, and downloadable >> distributions, see the Python 3.0 website: >> >> http://www.python.org/download/releases/3.0/ >> >> Enjoy, >> - -Barry >> >> Barry Warsaw >> [EMAIL PROTECTED] >> Python 2.6/3.0 Release Manager >> (on behalf of the entire python-dev team) > > uname -a > > Linux fetch 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:18:33 EDT 2007 x86_64 > x86_64 x86_64 GNU/Linux > > tar xzvf Python-3.0.tgz > cd Python-3.0 > ./configure > make > > Failed to find the necessary bits to build these modules: > _tkinter Do you have Tcl/Tk and their dev libs installed? Tkinter is based on Tcl/Tk. Also, that error isn't fatal, it just means that Tkinter won't be installed because it can't find the libs. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > To find the necessary bits, look in setup.py in detect_modules() for > the module's name. > > > Cheers, > Daniel > > > > > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I do this (from Perl) in Python? (closures)
On Wed, Dec 3, 2008 at 9:18 PM, <[EMAIL PROTECTED]> wrote: > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > ### > #!/usr/bin/env python > Depending on your version of Python, you need to do either (A) or (B). (A) requires Python 3.0 IIRC. > def make_counter(start_num): >start = start_num (B) replace prev line with: start = [start_num] >def counter(): (A) add:nonlocal start >start += 1 (B) replace prev line with: start[0] += 1 >return counter > > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() # 10 > print from_ten() # 11 > print from_three() # 3 > print from_ten() # 12 > print from_three() # 4 > > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. See http://www.python.org/dev/peps/pep-3104/ for more info. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > How can I do it in Python? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3 read() function
On Thu, Dec 4, 2008 at 8:57 AM, Cro <[EMAIL PROTECTED]> wrote: >> Do you really mean io.StringIO? I guess you want io.BytesIO() .. >> >> Christian > > Mmm... i don't know. > I also tried : > > [code] > IDLE 3.0 import io vContent = io.BytesIO() You do realize that the previous line is completely pointless, right? Later you rebind vContent to the results of huge.read() without ever having used it between that line and the above line. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com huge = io.open("C:\HUGE_FILE.pcl",'r+b',0) vContent = huge.read() > [/code] > > It still waits a lot... i don't have the patience to wait for the file > to load completely... it takes a lot! > > Thank you for your reply. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Why shouldn't you put config options in py files
On Thu, Dec 4, 2008 at 11:35 AM, HT <[EMAIL PROTECTED]> wrote: > A colleague of mine is arguing that since it is easy to write config like: > > FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} I'll assume you meant ('a', 'b') as colons in parens don't make sense. > > in config.py and just import it to get FOO, but difficult to achieve the > same using an ini file and ConfigParser, and since Python files are just > text, we should just write the config options in the Python file and > import it. > > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. > > Anyone? Well, it is pretty weird to be allowed to put arbitrary code in a mere config file. Have you considered using JSON for the config file format instead? It shares Python's syntax for literals, so you could do: $ cat config.json { "FOO": { "bar": ["a", "b"], "abc": ["z", "x"] } } Note that the whitespace doesn't matter. Also, you can use Python's built-on `json` module to parse the file. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Sat, Dec 6, 2008 at 1:33 PM, Carl Banks <[EMAIL PROTECTED]> wrote: > On Dec 5, 8:21 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]> > wrote: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value > > > > -1 > > I explained why deep in the thread but I'll elaborate more here. When > I see a def statement, I mentally equate that to an assigment to the > thing being def'ed. So for instance, when I see this: > > def (): > > I think of it like this: > > = > > > Thus, if I were to see a function definition like this > > def foo.bar(): return 1 > > I would think you were defining a function and assigning it to > foo.bar. IOW, it would be mostly equivalent to this: > > foo.bar = lambda: 1 > > > (Analogously, I would expect a definition like this: > > def baz[10](): return 1 > > to be equivalent to this: > > baz[10] = lambda: 1 ) > > > So, if, inside a class definition, I were to see this: > > def self.method(): return 1 > > Well, I'd understand that is was a method assigment, of course, but it > would conflict with what I would expect the natural meaning of > something like def a.b() would be. The above statement is not > equivalent to: > > self.method = lambda: 1 > > but I think that's what it ought to be, in general. Similarly, to those coming from Ruby or those operating under the frequent misunderstanding that the `def`s are happening in the context of a class object (which in reality has yet to be created), `self` in this context might be misconstrued as the class object and thus `def self.foo` might be misunderstood (through the intuitive equivalence you mention) as a defining a classmethod rather than an instance method. I also strongly echo the TOOWTDI arguments against adding this duplicative syntax. It's a minor gain but costs much more than it's worth for violating The Zen. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Carl Banks > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get a beep, OS independent ?
On Sat, Dec 6, 2008 at 3:40 PM, Stef Mientki <[EMAIL PROTECTED]> wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? Printing the http://en.wikipedia.org/wiki/Bell_character ("\a") to the terminal produces a beep from the internal speaker. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: can graphs be made in python as we make in java
On Sun, Dec 7, 2008 at 12:29 AM, suku <[EMAIL PROTECTED]> wrote: > HI folks... > > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. Python includes no such module for that in the standard library. You'll need to use a third-party library. If you're writing a webapp, pygooglechart (http://pygooglechart.slowchop.com/) is pretty good. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > help me out > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: var or inout parm?
On Sun, Dec 7, 2008 at 12:54 AM, <[EMAIL PROTECTED]> wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? Not directly possible or encouraged. You can emulate it by sticking the value in a container object (e.g. list) though: def f(x): x[0] += 1 #non-augmented assignment would work too n = [1] f(n) print n[0] #==> 2 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > def f(x): >x = x + 1 > > n = 1 > f(n) > # n should now be 2 > > Many TIA!! > Mark > > > -- > Mark Harrison > Pixar Animation Studios > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get a beep, OS independent ?
On Sun, Dec 7, 2008 at 1:27 AM, Stef Mientki <[EMAIL PROTECTED]> wrote: > Rainy wrote: >> >> On Dec 6, 3:40 pm, Stef Mientki <[EMAIL PROTECTED]> wrote: >> >>> >>> hello, >>> >>> I want to give a small beep, >>> for windows there's message-beep, >>> and there seems to be something like " curses" , >>> but that package seems to be totally broken in P2.5 for windows. >>> >>> Any other suggestions ? >>> >>> thanks, >>> Stef Mientki >>> >> >> For win there's winsound, you have to check sys.platform and do >> what's necessary for the platform in question. In linux I think >> you can just print '\a' (or does that only work in terminals?). >> If you know that ext. speakers are always on, you can do a nicer >> beep by using some wav file, in linux it's probably easiest to >> use an external program to play it, like wavplay. Basically, >> there is no single answer, it depends on circumstances. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > '\a' or chr(7) prints an inverted "BEL". Inverted bell? What do you mean? And what version dependency are you referring to? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > So it looks that Python version independency is even worse than OS > independency ;-) > I'll take a look at wxPython and Pygame if there's something useful. > > anyway thanks, > Stef > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: infering the number of args a function takes at runtime
On Sun, Dec 7, 2008 at 8:39 PM, sniffer <[EMAIL PROTECTED]> wrote: > hi all, > i am a python newbie, in a project currently doing i need to find out > the number of arguments that a function takes at runtime.? Is this > possible ,if so how do i do this,i ve looked through the python > documentation but couldnt find anything.any help will be great You want inspect.getargspec() or one of its friends in the `inspect` module. See http://docs.python.org/library/inspect.html#inspect.getargspec Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com I really should get back to studying now > > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about reference in Python.
On Sun, Dec 7, 2008 at 9:26 PM, Group <[EMAIL PROTECTED]> wrote: > Hello, I'm studying algorithom. For concentrating on the question itself, I > intend to use Python to implement the algorithoms. > > Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can > use pointers to refer to children notes (or next notes). But, in Python, > how > can I do it? Except the sequence, I know not any way. > > You'd better help me understan how can I transform the following C code into > Python: > > /* a List */ > struct { > int data; > int *next; > int *prev; > } Possibly not an exact literal translation, but: class ListNode(object): def __init__(self, data, prev=None, next=None) self.data = data self.prev = prev self.next = next Keep in mind that Python uses call-by-object (google it), so it doesn't have pointers/references per-se. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > That's all. Thanks! > Kermit > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about reference in Python.
On Sun, Dec 7, 2008 at 10:09 PM, James Mills <[EMAIL PROTECTED]> wrote: > Hi, > > This is really really really pointless code and a really really pointless > exercise, but nonetheless, here is a very very basic and minimal > implementation of what you're expecting. This should almost > *never* be done in Python! Python is a superior dynamic programming > language, but it's NOT C! > > Here goes: > > [EMAIL PROTECTED]:~/tmp$ ./list.py x[0] > 0 x[1] > 1 x[2] > 2 x[3] > 3 x[4] > Traceback (most recent call last): > File "", line 1, in > File "./list.py", line 36, in __getitem__ >return node.value > AttributeError: 'NoneType' object has no attribute 'value' > [EMAIL PROTECTED]:~/tmp$ > > And the code: > > #!/home/jmills/bin/python -i > > class Node(object): > The following three lines serve no purpose and can only lead to confusion: > value = None > prev = None > next = None > > def __init__(self, value, prev=None, next=None): > self.value = value > self.prev = prev > self.next = next > > class List(object): > Same with the following line. Why do you have these? Python does *not* have the concept of instance variable declaration. You are creating *class variables*, which is almost certainly not what you want. > data = None > Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > def __init__(self, *seq): > if seq: > first = prev = node = None > for x in seq: >if not first: > first = Node(x) > prev = node = first >else: > node = Node(x, prev) > prev.next = node > prev = node > > self.data = first > > def __getitem__(self, x): > node = self.data > for i in xrange(x): > node = node.next > return node.value > > x = List(0, 1, 2, 3) > > > Notes: > > I have not implemented any error checking whatsoever. > I have not implemented any of your normal list > operations whatsoever (except 1). __getitem__. > > Have fun, > > cheers > James > > On Mon, Dec 8, 2008 at 3:26 PM, Group <[EMAIL PROTECTED]> wrote: >> Hello, I'm studying algorithom. For concentrating on the question itself, I >> intend to use Python to implement the algorithoms. >> >> Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can >> use pointers to refer to children notes (or next notes). But, in Python, >> how >> can I do it? Except the sequence, I know not any way. >> >> You'd better help me understan how can I transform the following C code into >> Python: >> >> /* a List */ >> struct { >> int data; >> int *next; >> int *prev; >> } >> >> That's all. Thanks! >> Kermit >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > -- > -- "Problems are solved by method" > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about reference in Python.
On Sun, Dec 7, 2008 at 10:17 PM, James Mills <[EMAIL PROTECTED]> wrote: > On Mon, Dec 8, 2008 at 4:13 PM, Chris Rebert <[EMAIL PROTECTED]> wrote: >> The following three lines serve no purpose and can only lead to confusion: >>> value = None >>> prev = None >>> next = None > > You are absolutely right :) > > Updated code: > > > cheers > Jaems > > PS: Sorry Chris :) No apology necessary of course, i just didn't want the newbie OP to pick up any bad Python coding habits. Apologies that I might have phrased my criticism a bit harshly. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > -- > -- "Problems are solved by method" > -- http://mail.python.org/mailman/listinfo/python-list
Re: var or inout parm?
On Mon, Dec 8, 2008 at 12:26 AM, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Colin J. Williams a écrit : >> >> [EMAIL PROTECTED] wrote: >>> >>> How can I make a "var" parm, where the called function can modify >>> the value of the parameter in the caller? >>> >>> def f(x): >>>x = x + 1 >>> >>> n = 1 >>> f(n) >>> # n should now be 2 >>> >>> Many TIA!! >>> Mark >>> >>> >> >> Why not run it and see? >> >> Your function returns None. >> >> The function in effect takes a copy of n. > > Nope, it takes the object bound to global name 'n'. See Also: the earlier heated debate thread over what evaluation strategy Python uses (Survey says!: call-by-object). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime and the rich-companison operators
On Sun, Dec 7, 2008 at 11:41 PM, Ethan Furman <[EMAIL PROTECTED]> wrote: > Greetings All! > > I am implementing a NullDate class in order to mirror dates and datetimes > that have no value (yes, this is for my dbf module :) > > I'm still a bit fuzzy about class methods, hashing, and __new__, but my > question of the moment is this: it seems to me that with two dates or > datetimes, they should either be equal, or one should precede the other, and > this can be accomplished quite handily with __cmp__... so does anyone know > why the rich comparisons were used in the datetime module? Was it simply a > style choice, or is something being handled that __cmp__ couldn't cope with? Probably because __cmp__ was removed in Python 3.0, thus requiring the use of the rich comparison methods in its place. See the earlier thread entitled "Python 3 __cmp__ semantic change?". Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance! > ~ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling function from a string
On Mon, Dec 8, 2008 at 2:23 PM, Robert Dailey <[EMAIL PROTECTED]> wrote: > Hi, > > I have a string representing the name of a function in Python 3.0. How > can I call the function name represented by this string *without* > creating a mapping? Assuming the function is within scope: return_val = vars()[the_string](arguments, go, here) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Password input in console/terminal
On Mon, Dec 8, 2008 at 9:53 PM, RP <[EMAIL PROTECTED]> wrote: > Hello All, > > This is my first REAL post(question) to Python-List. I know I can take input > from a user with raw_input() > How do I take password input in console? Any Help would be Greatly > Appreciated. Thank You. RP You use the appropriately-named `getpass` module: http://docs.python.org/library/getpass.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: 'pretty print' for built in types
On Tue, Dec 9, 2008 at 7:31 AM, Robert Dailey <[EMAIL PROTECTED]> wrote: > Hi, > > Is there a built in way to 'pretty print' a dict, list, and tuple > (Amongst other types)? Dicts probably print the ugliest of them all, > and it would be nice to see a way to print them in a readable way. I > can come up with my own function to do this, but I don't want to do > this if I don't have to. There's the `pprint` module in the std lib: http://docs.python.org/library/pprint.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I manually uninstall setuptools (installed by egg)?
On Tue, Dec 9, 2008 at 6:49 PM, <[EMAIL PROTECTED]> wrote: > On Ubuntu, I accidentally manually installed setuptools > http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > as a shell script via sudo), and now realize I should just be using > apt to take care of my system Python packages. Really, why? setuptools has more Python packages/programs available and updates faster than Debian. It's also likely that some of the Debian Python packages are installed using setuptools anyway. So, why do you think apt and not setuptools is The Right Way(tm)? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I manually uninstall setuptools (installed by egg)?
On Tue, Dec 9, 2008 at 7:16 PM, <[EMAIL PROTECTED]> wrote: > On Dec 9, 10:04 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote: >> So, why do you think apt and not setuptools is The Right Way(tm)? > > I like to keep > 1 Python on my computer. Ah, now I get it. I had no idea setuptools could install Python *itself* until I checked just now. That's kinda neat, but mostly silly, because, as you point out, management of Python itself is much better left to the platform's package manager. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Deeper tracebacks?
On Wed, Dec 10, 2008 at 3:50 PM, brooklineTom <[EMAIL PROTECTED]> wrote: > On Dec 10, 5:03 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> > wrote: >> En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom <[EMAIL PROTECTED]> >> escribió: >> >> > I want my exception handler to report the method that originally >> > raised an exception, at the deepest level in the call-tree. Let give >> > an example. >> >> That's the default behavior, you don't have to do anything special. >> >> > import sys, traceback >> > class SomeClass: >> > def error(self): >> > """Raises an AttributeError exception.""" >> > int(3).zork() >> >> > def perform_(self, aSelector): >> > try: >> > aMethod = getattr(self, aSelector, None) >> > answer = apply(aMethod, [], {}) >> > except: AttributeError, anAttributeErrorException: >> > aRawStack = traceback.extract_stack() >> > answer = None >> >> (I assume you're using Python < 3.0) >> Use the 3-names form of the except statement: >> >> try: >> aMethod = getattr(self, aSelector, None) >> answer = aMethod() >> except AttributeError, e, tb: >> # the tb variable holds the traceback up to the error >> # the same thing you see printed by Python when >> # an unhandled error happens >> answer = None >> >> Alternatively, you can obtain the same thing with sys.exc_info()[2] >> Remember to delete any reference to the traceback object as soon as you're >> done with it; seehttp://docs.python.org/library/sys.html#sys.exc_info >> >> -- >> Gabriel Genellina > > I'm using Python 2.5. > > As I understand it, "aRawStack" (above) has the same information as > sys.exc_info()[2]. > > The deepest entry in aRawStack is the perform_ invocation. The > contents of the two bottom-most stack frames are: aRawStack[8][3] > "answer = anObject.perform_('error')" aRawStack[9][3] > 'aRawStack = traceback.extract_stack()' > > > By the time the handler is called, "zork" -- the method that was > called when the exception was raised, and "error", the method that > invoked zork, have already been removed from the stack. There is no zork() method, so it *can't have been called* and therefore *can't be in the traceback*. The error lies in the method that's trying to call a _nonexistent_ method, and that's where Python reports the error. Recall that: x.zork() is equivalent to: _z = x.zork #error occurs here, in the attribute lookup _z() #Python never gets here So no call takes place because you get an AttributeError before Python can get any further. zork() would only in the traceback if (1) it was looked up and called successfully [not the case here] and (2) an error occurred in zork()'s method body [again, not the case because it's not defined]. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: why doesn't pop/clear call __delitem__ on a dict?
On Wed, Dec 10, 2008 at 11:53 PM, Daniel Fetchinson <[EMAIL PROTECTED]> wrote: > I just found out that if I want to have a custom dict it's not enough > to overload __getitem__, __setitem__ and __delitem__ because, for > example, pop and clear don't call __delitem__. I.e. an instance of the > following will not print 'deleted' upon instance.pop( 'key' ): > > class mydict( dict ): >def __setitem__( self, key, value ): >print 'set' >super( mydict, self ).__setitem__( key, value ) >def __getitem__( self, key ): >print 'get' >super( mydict, self ).__getitem__( key ) >def __delitem__( self, key ): >print 'deleted' >super( mydict, self ).__delitem__( key ) > > Why is this? For optimization purposes essentially, so that the built-in dict can be as fast as possible as it is used pervasively in Python. > what other methods do I have to overload so that > I get what I expect for all dict operations? You might consider just subclassing UserDict.DictMixin instead: http://docs.python.org/library/userdict.html#UserDict.DictMixin It implements the complete dict interface all in terms of provided __getitem__(), __setitem__(), __delitem__(), and keys() methods. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Cheers, > Daniel > -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary as Keyword Arguments
On Thu, Dec 11, 2008 at 4:02 PM, bfrederi wrote: > I was wondering if I had a dictionary of keywords and values like so: > > keyword_arg_dict = { >'attribute': 'stone', >'contents': 'cave people', >'path': '/path/to/cave', >'name': 'Ogg's Cave', >} > > And I had a function that accepted keyword arguments like so: > > make_dwelling( >attribute='stone', >contents='cave people', >path='/path/to/cave', >name='Ogg's Cave', >) > > Is there any way I could use my keyword_arg_dict as my keyword args > for the make_dwelling function, since I am not the creator of the > make_dwelling function, and need to take that dictionary of key-value > pairs and turn it into keyword-value arguments for the make_dwelling > function? make_dwelling(**keyword_arg_dict) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: (Very Newbie) Problems defining a variable
On Fri, Dec 12, 2008 at 3:42 AM, wrote: > #!/usr/bin/python > #Py3k, UTF-8 > > > #determine the interest rate to use >if bank >= : >rate = 0.006 >elif bank >= 1 and bank <= 24999: >rate = 0.0085 >elif bank >= 25000 and bank <= 4: >rate = 0.0124 >elif bank >= 5 and bank <= 9: >rate = 0.0149 >elif bank >= 10: >rate = 0.0173 For the love of Benji, reverse the ordering of the clauses so you don't have to keep checking whether the number is also under the next limit! (I'm assuming Bruno's guess about your first test having the operator flipped around the wrong way was right) if bank >= 10: rate = 0.0173 elif bank >= 5: rate = 0.0149 elif bank >= 25000: rate = 0.0124 elif bank >= 1: rate = 0.0085 else: rate = 0.006 Note how much simpler that is to read and understand. And switching the default case to the 'else' is just idiomatic. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: var or inout parm?
On Fri, Dec 12, 2008 at 4:34 AM, sturlamolden wrote: > You cannot modify parameters by rebinding. x = x + 1 is a rebinding. x > += 1 is not. Python begs to differ, as those two statements are both semantically identical in this case: Python 2.6 (r26:66714, Nov 18 2008, 21:48:52) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = 2 >>> id (x) 8405372 >>> x += 1 >>> id(x) 8405360 >>> x = x + 1 >>> id(x) 8405348 If you were talking about lists rather than integers though, you'd be absolutely correct, as the += ends up being a method call to __iadd__ instead of a plain assignment. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: var or inout parm?
On Fri, Dec 12, 2008 at 4:56 AM, sturlamolden wrote: > On Dec 12, 1:44 pm, "Chris Rebert" wrote: > >> Python begs to differ, as those two statements are both semantically >> identical in this case: > > That is because integers are immutable. When x += 1 is done on an int, > there will be a rebinding. But try the same on say, a numpy array, and > the result will be different: Yes, I know that. Did you not read the end of my email? Here it is again: """ If you were talking about lists rather than integers though, you'd be absolutely correct, as the += ends up being a method call to __iadd__ instead of a plain assignment. """ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 crashes displaying Unicode at interactive prompt
On Sat, Dec 13, 2008 at 12:28 PM, John Machin wrote: > > Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. x = u'\u9876' x > u'\u9876' > > # As expected > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win 32 > Type "help", "copyright", "credits" or "license" for more information. x = '\u9876' x > Traceback (most recent call last): > File "", line 1, in > File "C:\python30\lib\io.py", line 1491, in write >b = encoder.encode(s) > File "C:\python30\lib\encodings\cp850.py", line 19, in encode >return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in > position > 1: character maps to > > # *NOT* as expected (by me, that is) > > Is this the intended outcome? When Python tries to display the character, it must first encode it because IO is done in bytes, not Unicode codepoints. When it tries to encode it in CP850 (apparently your system's default encoding judging by the traceback), it unsurprisingly fails (CP850 is an old Western Europe codec, which obviously can't encode an Asian character like the one in question). To signal that failure, it raises an exception, thus the error you see. This is intended behavior. Either change your default system/terminal encoding to one that can handle such characters or explicitly encode the string and use one of the provided options for dealing with unencodable characters. Also, please don't call it a "crash" as that's very misleading. The Python interpreter didn't dump core, an exception was merely thrown. There's a world of difference. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky nested list unpacking problem
On Mon, Dec 15, 2008 at 11:06 AM, Reckoner wrote: > Hi, > > I have lists of the following type: > > [1,2,3,[5,6]] > > and I want to produce the following strings from this as > > '0-1-2-3-5' > '0-1-2-3-6' > > That was easy enough. The problem is that these can be nested. For > example: > > [1,2,3,[5,6],[7,8,9]] > > which should produce > > '0-1-2-3-5-7' > '0-1-2-3-5-8' > '0-1-2-3-5-9' > '0-1-2-3-6-7' > '0-1-2-3-6-8' > '0-1-2-3-6-9' > > also, > > [1,2,3,[5,6],7,[9]] > > should produce > > '0-1-2-3-5-7-9' > '0-1-2-3-6-7-9' > > obviously, these are nested loops over the lists. The problem is that > I don't know ahead of time how many lists there are or how deep they > go. In other words, you could have: > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > Any help appreciated. I've really been having trouble with this. > > I hope that made sense. You just need a recursive list-flattening function. There are many recipes for these. Here's mine: def flatten(lst): if isinstance(lst, list): result = [] for item in lst: result += flatten(item) return result else: return [lst] >>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>> flattened [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>> '-'.join(str(num) for num in flattened) '1-2-3-5-6-10-11-7-9-1-2-3-4-5' Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem accessing a web page
On Mon, Dec 15, 2008 at 11:55 AM, Antoni Mont wrote: > Hi all, > > My apologises if this is not the appropriate group. > > I'd like to access a web site from a python script. That page, in fact, > is a form of main page. With a browser (Firefox, for instance) I can do > it without problem: I open the main web whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es' > > and then, from the same (or another tab) I open the form (it's a book > database and the ISBN is the relevant parameter) whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn' > > So I get the information about the book. > > But when I try to do the same from the script, I get a time-out > error -without time elapsing at all. This is the piece of the > script relevant for the subject: I'm able to grab the problem webpage via Python just fine, albeit with a bit of a delay. So, don't know what your exact problem is, maybe your connection? If you're trying to programmatically browse the web, you might want to look at mechanize: http://wwwsearch.sourceforge.net/mechanize/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky nested list unpacking problem
On Mon, Dec 15, 2008 at 12:24 PM, Kirk Strauser wrote: > At 2008-12-15T20:03:14Z, "Chris Rebert" writes: > >> You just need a recursive list-flattening function. There are many >> recipes for these. Here's mine: > >>>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>>>> flattened >> [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>>>> '-'.join(str(num) for num in flattened) >> '1-2-3-5-6-10-11-7-9-1-2-3-4-5' > > He doesn't want to flatten them directly. He's using [1,2,3] sort of like a > regular expression, so that 1,[2,3],4 means "1,2,4" or "1,3,4", not > "1,2,3,4". Ah, my bad. Misinterpreted. Still, it's a similar principle involved. He just needs to code up the right recursive function. Not all that hard. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: parse C expression?
On Mon, Dec 15, 2008 at 3:48 PM, Torsten Mohr wrote: > Hi, > > i found some examples when googling for the subject but nothing really > matched. > > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? > > I'd like to use this to parse an own kind of configuration language > and preferred would be just standard modules. Is there something > available that is maybe based on shlex? No, nothing approaching C-syntax as it'd have be much more complicated than shlex and I can't imagine too many uses for such a module. If it's a configuration file, you might consider using either JSON (std lib module `json`) or INI (std lib module `ConfigParser`) as the format instead. Or if you need something really complex, just use Python itself. Custom config file formats are bad anyway. Should you have no control over the format, you'll need to write a proper parser grammar with something like pyparsing as was mentioned by James. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Free place to host python files?
On Tue, Dec 16, 2008 at 6:10 AM, feba wrote: > I'm getting started in python, and it would be helpful to have a place > to put up various code snippets I've made, so I don't have to send > them individually to each person I want to show it to. I'd prefer to > use something that would give me a directory for my use only, instead > of something where you can only upload one at a time. I'd especially > like to avoid stuff that uses CAPTCHAs and/or forced waiting periods. > > I'd really rather not have to run a server off my own computer, if it > can be avoided at all. I'll plug Bitbucket (http://bitbucket.org/). It gives you 150MB of Mercurial hosting for free, along with a bug tracker and wiki. And I hear it's implemented using Django. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: The rule of literal string
On Tue, Dec 16, 2008 at 9:32 PM, Li Han wrote: > Hi! I just began to read the tutorial of python3.0 and I just can't > figure out the rule of literal string. There is a example in the > tuotrial: '"Isn\'t," she said.' > '"Isn\'t," she said.' > It is not what I want, I just want '"Isn't," she said.' be printed, > why the backslash failed? > These don't work at all: '''"Isn't," she said.''' > '"Isn\'t," she said.' r"Isn't," she said. > SyntaxError: invalid syntax (, line 1) r'"Isn't," she said.' > SyntaxError: invalid syntax (, line 1) > I have tried to solve it until my brain damaged and now I need to > sleep. You need to print() the string. Otherwise, the interpreter does an implicit repr() on the string, causing it to output a string literal equivalent to the string, essentially doing print(repr(your_string)). To explain what repr() does, consider the following identity: eval(repr(your_string)) == your_string Notice how the outer set of quotes is still present in the output you got. Using print() explicitly causes repr() not to be called, thus the escape backslashes aren't shown and neither are the surrounding quotes. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Selecting a different superclass
On Wed, Dec 17, 2008 at 6:41 AM, psaff...@googlemail.com wrote: > This might be a pure OO question, but I'm doing it in Python so I'll > ask here. > > > The problem is that IDPointSet and MicroArrayPointSet will need to > inherit from PointSet or TraceablePointSet based on whether I'm > handling traceable points or not. Can I select a superclass > conditionally like this in Python? Am I trying to do something really > evil here? You're doing something really dynamic; don't think I'd call it inherently evil though. All you have to do is use a variable in the inheritance syntax, it's really quite simple: superclass = TraceablePointSet if tracing else PointSet class IDPointSet(superclass): #body code here #use same trick for MicroArrayPointSet Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: something else instead of PIL?
On Wed, Dec 17, 2008 at 12:48 PM, Reimar Bauer wrote: > Hi > > what has happened to PIL? No updates since two years. The Python Imaging Library is still current; I guess they just haven't found any new bugs or seen fit to add new functionality in a while, though I presume they'll start working on a Python 3.0 port eventually. If you don't like PIL, there's always the (much less popular) Python bindings to ImageMagick: http://www.imagemagick.org/script/api.php#python Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: The rule of literal string
2008/12/17 Li Han : > On 12月18日, 上午7时12分, Scott David Daniels wrote: > Scott wrote: >> Try: print repr(repr("'")) >> that might enlighten you. > > I found that print( repr( repr( arbitarystring ) ) ) == repr > ( arbitarystring ) As I stated previously, the key rule is: eval(repr(something)) == something That is, repr() gives a string of Python code that, when evaluated, results in what you gave to repr(). So repr('') ==> "''" And repr("''") ==> "\"''\"" Which when print()-ed is: "''" And eval("''") is the same as entering two apostrophes ('') at the REPL, both of which give an empty string object. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: The rule of literal string
On Wed, Dec 17, 2008 at 3:34 PM, James Mills wrote: > On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert wrote: >> As I stated previously, the key rule is: >> >> eval(repr(something)) == something > > This rule is only true for basic data types; > > For example: > >>>> eval(repr(1)) == 1 > True >>>> eval(repr([1, 2, 3])) == [1, 2, 3] > True >>>> eval(repr({"a": 1, "b": 2, "c": 3})) == {"a": 1, "b": 2, "c": 3} > True >>>> eval(repr("foo")) == "foo" > True > > I guess the key thing here is that the repr > implementation (__repr__) for str, int, float > list and dict return sensible represenations > that Python _can_ evaluate with eval(...) > > --JamesMills > True, I oversimplified to make things easier to understand. Strictly speaking, only the basic types make the guarantee I stated. Arbitrary types can have arbitrary, non-eval()-able repr()s. But the docs do state eval()-ability as a goal: repr(object) Return a string containing a printable representation of an object. [...] For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: The rule of literal string
On Wed, Dec 17, 2008 at 3:52 PM, Li Han wrote: > Chris worte: > [snip] >> And repr("''") ==> "\"''\"" >> Which when print()-ed is: "''" >> And eval("''") is the same as entering two apostrophes ('') at the >> REPL, both of which give an empty string object. > > On my machine: repr("''") > '"\'\'"' > Han Well, I was kinda winging it and didn't actually use the interpreter for some of those. The point is that the output I gave _could_ reasonably be that of the interpreter (if the implementation details of repr() were slightly different; it would still meet the spec anyway) and illustrates the eval()-repr() relationship. Just keep in mind the equivalence rule and what repr() does should become obvious. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no lexical scoping for a method within a class?
On Wed, Dec 17, 2008 at 4:03 PM, Rhodri James wrote: > On Wed, 17 Dec 2008 15:19:32 -, walterbyrd wrote: > >> However in the methods are within a class, the scoping seems to work >> differently. > > Not really. Hopefully this commentary will show you why. > >> class ab(): >>def a(self): >>self.x = 99 >>print self.x >>def b(self): >>print self.x >> >> i = ab() > > This creates |i|, an instance of class |ab|. As yet it is pure and virgin, > having nothing but the methods that it gets from |ab|. Soon this will > change... > >> i.a() > > This creates an attribute |x| in |i|, and assigns the number 99 to it. > >> i.b() # this works, why no lexical scoping? > > This works because you ran |i.a()| first, so |i.x| exists and can be printed > out. Lexical scoping is going on here, you're just mistaking what's being > scoped; it's the |self| in |b|, which is in scope because it's a parameter. > This particular |self| (the |i| you made earlier) happens to have an > attribute |x|, so it all works. If however you'd written: > > j = ab() > j.b() > > then Python would whinge mightily at you, claiming that it knoweth naught of > this |x| attribute of which you speak, and can it go home now for this is a > silly place. The |self| in |b| is still in lexical scope, though. > Relatedly, Python has no notion of 'declaring' instance variables in a class (instead, you just create them in __init__ or other methods), and class variables (in Java terminology: 'static' variables) do not constitute a scope for variable lookup. Python is still lexically scoped, it's just that only functions and the "globals"/toplevel/module-level constitute scopes, not class bodies. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: importing csv file into sqlite
On Wed, Dec 17, 2008 at 9:58 PM, klia wrote: > > hey guys, i have a hug .csv file which i need to insert it into sqlite > database using python. > my csv data looks like this > Birthday2,12/5/2008,HTC,this is my birthday > Sea,12/3/2008,kodak,sea > birthday4,14/3/2009,samsung,birthday > love,17/4/2009,SONY,view of island > > can any one give me a head start codes. > Use the `csv` module to read the CSV file: http://docs.python.org/library/csv.html I think one who knows sqlite can quite easily figure it out from there. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list