MSN Bot Class
## # MsnClient Class -- A basic class that enables one to create an MSN client this way: # x = MsnClient(to_msnid, bot_msnid, bot_msnid_password, messege); x.tell() # (C) Timothy Makobu, 2007 ## import select import socket import thread import msnlib import msncb import time import sys class MsnClient: def __init__(self, to_id='', bot_id='', bot_pass='', message='Hi :D'): MsnClient(to_msnid, bot_msnid, bot_msnid_password, messege) self.to_id = to_id self.message = message self.msn_obj = msnlib.msnd() self.msn_obj.cb = msncb.cb() self.msn_obj.email = bot_id self.msn_obj.pwd = bot_pass self.msn_obj.login() self.msn_obj.sync() self.msn_obj.change_status('online') def _send_message(self): time.sleep(15) print 'Here 2' print 'here 3', self.msn_obj.sendmsg(self.to_id, self.message) time.sleep(30) self._quit() def _quit(self): try: self.msn_obj.disconnect() except: pass sys.exit(0) def tell(self): thread.start_new_thread(self._send_message, ()) while 1: self.nd = self.msn_obj.pollable() self.in_fd = self.nd[0] self.out_fd = self.nd[1] try: self.poller = select.select(self.in_fd, self.out_fd, [], 0) except: self._quit() for self.i in self.poller[0] + self.poller[1]: try: self.msn_obj.read(self.i) except('SocketError', socket.error), err: if self.i != self.msn_obj: self.msn_obj.close(self.i) else: self._quit() time.sleep(0.1) -- http://mail.python.org/mailman/listinfo/python-list
Accessing Function Variables from Sub-functions
On Apr 14 2003, 10:30 pm, Alex Martelli [EMAIL PROTECTED] wrote: Sebastian Wilhelmi wrote: Hi, I would like to do the following: ---8---8---8---8--- def test (): count = 0 def inc_count (): count += 1 inc_count () inc_count () print count test () ---8---8---8---8--- This doesn't work (and I even understand, why ;-) Specifically: a nested function cannot *RE-BIND* a variable of an outer function. Sorry to dig up this old thread, but I would like to know what's the rationale is. Why can't a nested function rebind a variable of an outer function? One solution is the following, which I however do not see as very clean or nice. ---8---8---8---8--- def test (): count = [0] def inc_count (): count[0] += 1 inc_count () inc_count () print count[0] test () ---8---8---8---8--- Now my question: Is there some way to achieve this with a nicer syntax? Depends on your tastes in syntax, e.g.: def test(): class Bunch: pass loc = Bunch() loc.count = 0 def inc_count(): loc.count += 1 inc_count() inc_count() print loc.count or: def test(): test.count = 0 def inc_count(): test.count += 1 inc_count() inc_count() print test.count and no doubt quite a few others. I was trying to write a function that creates another function and returns it when I came across this problem. These two solutions have a difference: def M(): M.c = 0 class Bunch: pass Bunch.c = 0 def f(): M.c += 1 Bunch.c += 1 print M.c, Bunch.c return f f = M() f2 = M() f() 1 1 f() 2 2 f() 3 3 f2() 4 1 f2() 5 2 f2() 6 3 The created functions share their variables binded to the outer function, but have their separate copies of variables bundled in a class. Is binding name to the function object a python way to use 'static' variables? But how to initialize them? Using 'global' would not count, as that would make a variable unnecessarily known to the outside. The two solutions above outlined differ in this respect -- variable 'loc' in the former is local to function test, while function attribute test.count in the latter is known to the outside (it survives each execution of test and can be examined from the outside). Class Bunch (or some highly refined version thereof) IS typically around whenever I program, see for example: http://mail.python.org/pipermail/python-list/2002-July/112007.html for a typical presentation. Having available the MetaBunch there described, I'd start the function as follows: def test(): class Bunch(MetaBunch): count=0 loc = MetaBunch() def inc_count(): loc.count += 1 etc. I do find such constructs often handy... Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: multimethods decorator
[EMAIL PROTECTED] a écrit : Gerardo Herzig a écrit : Hi all. Im reading the Gido's aproach using decorators at http://www.artima.com/weblogs/viewpost.jsp?thread=101605 It looks good to me, but the examples shows the functionality using functions. Now, when i try to give this decorator into a method, if i try the class test(object): @multimethod(...) def met(self, ...): The multimethod decorator needs the types of the arguments, and, if the met method requires self as the first argument, the multimethod should look like @multimethod(self.__class__, bla, ble) or some like that... Now i know that im wrong, because i have this error @multimethod(self.__class__) NameError: name 'self' is not defined Indeed. Neither self (which will only be known at method call time) nor even the 'test' class (which is not yet defined when the decorator is executed) are availables. Doh! If you're surprised, then you'd better learn way more about Python's internal (execution model object model mostly) before continuing with multimethods. So what would be the first argument to @multimethod?? A string ?-) Ah? And what will that string contains? What makes sens for you. Don't forget that Python has very strong introspection features. Also note that it's not uncommon to use a 2-pass approach : marking some methods with the decorator, then doing the real processing in the metaclass (which of course implies a custom metaclass) or in the __new__ method (in which case this processing will happen on *each* instanciation). FWIW, there's already an implementation of multiple dispacth by Mr. Eby... Oh yes, i found the dispatch version of multimethods, but i have not tried it yet. Do you think is better this version than Guido's? I think that dispatch is actually used in a few packages, frameworks or applications. Is it the case of Guido's stuff ? Also, IIRC, Guido's snippet is quite less generic than dispatch (which is based on expression rules, not only on types). My 2 cents... -- http://mail.python.org/mailman/listinfo/python-list
Py2exe with PyQt4 and sqlite
I wrote an application that uses PyQt4 to access a sqlite DB. Now I'm trying to convert it using py2exe and I found some problems. The last one, that I'm not able to avoid, is that when I launch the application's binary on a PC (that contains only a Python 2.5 installation and no QT4) I get an error trying to open the DB withi this code: db = QtSql.QSqlDatabase.addDatabase(QSQLITE) db.setDatabaseName(defines.DB_FILE) if not db.open(): # displays: Driver not loaded. I made many attempts changing options in my setup file but none of them successfull. The last one uses this options: options={py2exe: {includes:[sip, 'PyQt4.QtSql' ], packages: [sqlite3,]}} but I verified that neither QtSql, neither sqlite3 are usefull to avoid the error. My development configuration is Python 2.5 Qt4 4.2.2 PyQt4.1.1 Any suggestion to solve this problem? Thanks in advance. Ciao. Licia. -- http://mail.python.org/mailman/listinfo/python-list
gdbm troubles.
dictionary = gdbm.open('dictionary','c') dictionary['Ellipsize'] = 'Openbox' dictionary.get('Ellipsize') the last line generates an attribute error. Can someone tell me what I am doing wrong? Regards, Shriphani Palakodety -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with struct.pack()
On Wed, 10 Oct 2007 22:19:49 -0500, Robert Dailey wrote Hi, Thanks for responding. I apologize about my lack of details, I was in a hurry when I wrote the initial question. I'll provide more details. Basically, I'm attempting to write out unicode strings (16 bits per character) to a file. Before each string, I write out 4 bytes containing the number of characters (NOT BYTES) the string contains. I suppose the confusion comes in because I'm writing out both text information AND binary data at the same time. I suppose the consistent thing to do would be to write out the strings as binary instead of as text? I'm originally a C++ programmer and I'm still learning Python, so figuring out this problem is a little difficult for me. In my initial inquiry, I was writing out 5000 as an example, however this number would realistically be the number of characters in the string: len( uHello World ). Once I write out these 4 bytes, I then write out the string Hello World immediately after the 4 bytes. You may be wondering why the crazy file format. The reason is because this python script is writing out data that will later be read in by a C++ application. The following works fine for ASCII strings: mystring = Hello World file = open( somefile.txt, wb ) file.write( struct.pack ( I, len(mystring) ) ) file.write( mystring ) Again I do apologize for the lack of detail. If I've still been unclear please don't hesitate to ask for more details. This is much clearer, and it explains why you need to mix arbitrary binary data with unicode text. Because of this mixing, as you have surmised, you're going to have to treat the file as a binary file in Python. In other words, don't open the file with the codecs module and do the encoding yourself, like so: mystring = uHello World file = open( somefile.txt, wb ) file.write( struct.pack ( I, len(mystring) ) ) file.write( mystring.encode(utf-16-le) ) (Note that I've guessed that you want little-endian byte-order in the encoding. Without that indication, encode() would put a byte order mark at the beginning of the string, which you probably don't want.) Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is hostmonster any good for hosting python?
On Oct 10, 1:27 pm, walterbyrd [EMAIL PROTECTED] wrote: According to hostmonster's list of features, they do support python. Does anybody have any experience with hostmonster? I'm using host monster to run my html-only site. However, I want to add some python cgi, and I'd prefer to extend that to the Django framework. I've had some issues getting cgi support. I've IM'd with a tech rep and all they could tell me is that yes, they do support python cgi. From what I've seen, they don't have the mod_python module installed for Apache. Without mod_python, I don't think you can install Django. Not sure about other pythonic web frameworks. Outside of the cgi support, host monster has been pretty good to work with. They have a pretty slick control panel. Also, they use CentOs 4 and an older version of python. HTH, J -- http://mail.python.org/mailman/listinfo/python-list
Re: Is hostmonster any good for hosting python?
According to hostmonster's list of features, they do support python. Does anybody have any experience with hostmonster? I'm using host monster to run my html-only site. However, I want to add some python cgi, and I'd prefer to extend that to the Django framework. I've had some issues getting cgi support. I've IM'd with a tech rep and all they could tell me is that yes, they do support python cgi. From what I've seen, they don't have the mod_python module installed for Apache. Without mod_python, I don't think you can install Django. Not sure about other pythonic web frameworks. While vanilla CGI is a really bad idea for Django, in addition to mod_python, Django supports FastCGI for deployment if your hosting service doesn't give you mod_python access. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Function Variables from Sub-functions
Licheng Fang wrote: On Apr 14 2003, 10:30 pm, Alex Martelli [EMAIL PROTECTED] wrote: Sebastian Wilhelmi wrote: Hi, I would like to do the following: ---8---8---8---8--- def test (): count = 0 def inc_count (): count += 1 inc_count () inc_count () print count test () ---8---8---8---8--- This doesn't work (and I even understand, why ;-) Specifically: a nested function cannot *RE-BIND* a variable of an outer function. Sorry to dig up this old thread, but I would like to know what's the rationale is. Why can't a nested function rebind a variable of an outer function? Because the lack of variable declarations in python makes the left-hand-side-appearance of a variable the exact distinction criteria between inner and outer scopes. Thus it can't rebind them. What you can do is to use mutables as container for outer variables: def outer(): v =[1] def increment(): a = v[0] a += 1 v[0] = a increment() print v[0] Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: gdbm troubles.
On Thu, 11 Oct 2007 11:49:05 +, Shriphani wrote: dictionary = gdbm.open('dictionary','c') dictionary['Ellipsize'] = 'Openbox' dictionary.get('Ellipsize') the last line generates an attribute error. Can someone tell me what I am doing wrong? You are trying to use a method that does not exist. That `gdbm` object doesn't have a `get()` method. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
On Thu, 11 Oct 2007 11:48:18 +, Artur Siekielski wrote: class Person(object): def __init__(self, name): self._name = name def _get_name(self): return self._name def _set_name(self, new_name): self._name = new_name name = property(_get_name, _set_name) This is more easily spelled: class Person(object): def __init__(self, name): self.name = name I would like to have something like that: class Person(object): name = property('_name') I assume that this causes generation of instance field '_name' and default getters and setters. But why? Default getters and setters are unnecessary and if you need something other than the default you need to write it anyway more explicitly. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Duck Typing and **kwds
On 10/11/07, Luis Zarrabeitia [EMAIL PROTECTED] wrote: Hi there. I just tried this test: def f(**kwds): print kwds import UserDict d = UserDict.UserDict(hello=world) f(**d) And it fails with a TypeError exception (f() argument after ** must be a dictionary). I find that weird, as UserDict should support all protocols that dict supports, yet it doesn't seem to support ** unpacking. If instead of UserDict I use a derivate class from dict (class mydict(dict):pass), the ** operator works as expected. It also works if I execute f(**dict(d)) instead. Is that behavior expected? Is there any reason (performance, perhaps?) to break duck-typing in this situation? Reported, accepted and closed 5 months ago: http://bugs.python.org/issue1686487 -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: But why? Default getters and setters are unnecessary and if you need something other than the default you need to write it anyway more explicitly. I see some problems with your approach: 1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value. 2. Properties define (a part of) public interface of a class. When using fields for public access, you must tell this explicitly in documentation, or use name convention. And public fields definition is mixed with private fields, which doesn't happen when using properties. 3. Using properties as first-class objects gives possibilities to use declarative approaches for constructing them. -- http://mail.python.org/mailman/listinfo/python-list
RE: RMI with Pyro et al
Diez B. Roggisch wrote . Why do you want that (hot deploy) anyway? Does startuptime of a script really bother you? shouldn't take more than a few seconds. My primary need is development/debug. I'm a Pyro newbie and I add a feature and then test. The only way I've found to kill the Pyro server on XP is to open the task manager and kill the python task (hopefully the right one). -- http://mail.python.org/mailman/listinfo/python-list
Problem with MySQL cursor
Hello, I have a function that executes a SQL statement with MySQLdb: def executeSQL(sql, *args): print sql % args cursor = conn.cursor() cursor.execute(sql, args) cursor.close() it's called like that: sql = INSERT INTO %s (%s) VALUES (%s) executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) The statement that is printed looks ok (missing quotes, but AFAIK cursor.execute does that): INSERT INTO domains (domain) VALUES (xgm.de) but MySQL prints an error: Traceback (most recent call last): File manage.py, line 90, in ? addDomain(domainName) File manage.py, line 27, in addDomain executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) File manage.py, line 22, in executeSQL cursor.execute(sql, args) File /usr/lib/python2.4/site-packages/MySQLdb/cursors.py, line 163, in execute self.errorhandler(self, exc, value) File /usr/lib/python2.4/site-packages/MySQLdb/connections.py, line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''domains' ('domain') VALUES ('xgm.de')' at line 1) I see the error: 2 opening quotes but only 1 closing around domains. But where do they come from? Note that there are no quotes at print sql % args. Thanks, Florian -- http://mail.python.org/mailman/listinfo/python-list
Re: Fwd: NUCULAR fielded text searchable indexing
On Oct 11, 3:30 am, Paul Rubin http://[EMAIL PROTECTED] wrote: Delaney, Timothy (Tim) [EMAIL PROTECTED] writes: As for [ http://nucular.sourceforge.net ] itself, I've only had a chance to glance at the site... Thanks for taking a look. I hope you don't mind if I disagree with a number of your comments below. ...but it looks a little more akin to Solr than to Lucene. Solr is a Java application that wraps Lucene to present a more convenient interface I'm not sure but I think nucular has aspects of both since it implements both the search engine itself and also provides XML and HTTP interfaces, like http://www.xfeedme.com/nucular/gut.py/go ...although it does this using XML over an HTTP socket. One thing about Solr and probably anything else like this: if you want to handle a high query load with big result sets, you absolutely must have enough ram to cache your entire index. ... Of course it would be nice to have everything in RAM, but it is not absolutely necessary. In fact you can get very good performance with disk based indices, especially when the index is warm and the most heavily hit disk buffers have been cached in RAM by the file system. As a test I built an index with 10's of millions of entries using nucular and most queries through CGI processes clocked in in 100's of milliseconds or better -- which is quite acceptable, for many purposes. ...Since ram is expensive and most of it will be sitting there doing nothing during the execution of any query, it follows that you want multiple CPU's sharing the ram. So we're back to the perennial topic of parallelism in Python... ...Which is not such a big problem if you rely on disk caching to provide the RAM access and use multiple processes to access the indices. The global interpreter lock (GIL) can be kinda nice sometimes too. When I built the big indices mentioned above it took a long time. If I had used a multithreaded build my workstation would have been worthless during this time. As it was I was using Python in a single process, so the other CPU was happy to work with me during the build, and I hardly noticed any performance degradation. In one java shop I worked in the web interface worked ok (not great) provided it was only hit by one access at a time, because the system was engineered so that one access consumed all computational resources on the box. Of course if you hit it continually with 4 concurrent accesses the system went to its knees and got tangled up in livelocks and other messes. In the case of web apps it can be very nice to have one access handled by one process in one thread leaving the other cpu's available to handle other accesses or do other things. imho, fwiw, ymmv, rsn, afaik. -- Aaron Watters === even in a perfect world where everyone is equal i'd still own the film rights and be working on the sequel -- Elvis Costello Every day I write the book -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with MySQL cursor
On Thu, Oct 11, 2007 at 03:14:30PM +0200, Florian Lindner wrote regarding Problem with MySQL cursor: Traceback (most recent call last): File manage.py, line 90, in ? addDomain(domainName) File manage.py, line 27, in addDomain executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) File manage.py, line 22, in executeSQL cursor.execute(sql, args) File /usr/lib/python2.4/site-packages/MySQLdb/cursors.py, line 163, in execute self.errorhandler(self, exc, value) File /usr/lib/python2.4/site-packages/MySQLdb/connections.py, line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''domains' ('domain') VALUES ('xgm.de')' at line 1) I see the error: 2 opening quotes but only 1 closing around domains. But where do they come from? Note that there are no quotes at print sql % args. No, there are no double quote issues. The first quote is provided by the error message, and is paired with the quote after the closed parenthesis in ('xgm.de')'. It is not part of your SQL. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Re: matching a street address with regular expressions
Don't forget to write test cases. If you have a series of addresses, and confirm they are parsed correctly, you are in a good position to refine the pattern. You will instantly know if a change in pattern has broken another pattern. The reason I'm saying this, is because I think your pattern is incomplete. I suggest you add a test case for the following street address: 221B Baker Street That is a real address in London (only Sherlock Holmes) was fiction. I know it, because I actually visited the location. Can you address matching pattern handle that? Just don't break other address recognition test cases while fixing things. -- http://mail.python.org/mailman/listinfo/python-list
RE: Problem with MySQL cursor
I don't think you can substitute the table name and column names in the execute, just values ( I could be wrong) try building it like this: sql = INSERT INTO %s %s VALUES % (taablename, columnstuple, '(%s)') cursor.execute(sql, values) Hello, I have a function that executes a SQL statement with MySQLdb: def executeSQL(sql, *args): print sql % args cursor = conn.cursor() cursor.execute(sql, args) cursor.close() it's called like that: sql = INSERT INTO %s (%s) VALUES (%s) executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) The statement that is printed looks ok (missing quotes, but AFAIK cursor.execute does that): INSERT INTO domains (domain) VALUES (xgm.de) but MySQL prints an error: Traceback (most recent call last): File manage.py, line 90, in ? addDomain(domainName) File manage.py, line 27, in addDomain executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) File manage.py, line 22, in executeSQL cursor.execute(sql, args) File /usr/lib/python2.4/site-packages/MySQLdb/cursors.py, line 163, in execute self.errorhandler(self, exc, value) File /usr/lib/python2.4/site-packages/MySQLdb/connections.py, line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''domains' ('domain') VALUES ('xgm.de')' at line 1) I see the error: 2 opening quotes but only 1 closing around domains. But where do they come from? Note that there are no quotes at print sql % args. Thanks, Florian -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with MySQL cursor
On Thu, 2007-10-11 at 15:14 +0200, Florian Lindner wrote: Hello, I have a function that executes a SQL statement with MySQLdb: def executeSQL(sql, *args): print sql % args cursor = conn.cursor() cursor.execute(sql, args) cursor.close() it's called like that: sql = INSERT INTO %s (%s) VALUES (%s) executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) You can't use parameter binding to substitute table names and column names, or any other syntax element, into a query. You can only bind parameters in places where a literal value would be allowed (more or less, the real rules are more complicated, but this rule of thumb gets you close enough). You have to construct the query string like this, for example: sql = INSERT INTO +DOMAIN_TABLE+(+DOMAIN_FIELD+) VALUES (%s) executeSQL(sql, domainname) HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Script to Remove Attachments in Exchange Mailbox
Hi, I am frustrated with my users who send large files around the office instead of using the network shares. For instance, this is one of many emails I have sent around: If you take the this kit it looks like J sent it to D, D sent it to you, then you sent it to me. The problem with that is just that now there are copies of this file: On J's drive or Comm drive J's sent items D's inbox D's sent items Your inbox Your sent items My inbox The comm. Drive once I save it there to be used. Which means that there are 8 copies of the same file 4MB taking up space, or a 4MB file turned into a 32MB file. My users just aren't getting it! And then they complain when they get quota messages! (and some people, when they are Important People, you cannot argue with). So, what I would like, is to write a script that parses the exchange mailbox, and removes all attachments over a certain size (say 500K) that are attached to messages that are more than 2 weeks old, or that are in sent items. I would like to write to a log file all the changes that are made then email that log file to the mailbox that was just trimmed. I will also like to have a verbose mode that allows the user when the script is run to ok each removal. I am trying to decide if I should do this in Python or VBScript. Any suggestions? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: gdbm troubles.
Shriphani wrote: dictionary = gdbm.open('dictionary','c') dictionary['Ellipsize'] = 'Openbox' dictionary.get('Ellipsize') Try this: print dictionary['Ellipsize'] del dictionary['Ellipsize'] gdbm objects are similar to builtin dictionaries. By the way, they are not iterable, but they should be. I posted a proposal some days ago and nobody was against this. How can I start a discussion about this? Can we vote for this new feature here? Is this the right place? Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
On Thu, 11 Oct 2007 13:04:53 +, Artur Siekielski wrote: On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: But why? Default getters and setters are unnecessary and if you need something other than the default you need to write it anyway more explicitly. I see some problems with your approach: 1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value. So what? Otherwise you carry *always* the baggage of a public property and a private attribute whether you need this or not. At least for me it would be unnecessary in most cases. 2. Properties define (a part of) public interface of a class. When using fields for public access, you must tell this explicitly in documentation, or use name convention. And public fields definition is mixed with private fields, which doesn't happen when using properties. Attributes are public unless you start the name with an underscore which is by convention a warning to not use that attribute unless you know what you are doing. With properties all over the place you use that convention anyway because the real value for `name` is bound as `_name`. So you clutter your API with two attributes for non-method-attributes. And a property is not automatically part of the public API, just if the name does not start with an underscore. 3. Using properties as first-class objects gives possibilities to use declarative approaches for constructing them. No idea what you mean here. Everything in Python is an object. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: matching a street address with regular expressions
Check out kodos http://kodos.sourceforge.net/ for an interactive python regexp tester Andy Goldfish wrote: Don't forget to write test cases. If you have a series of addresses, and confirm they are parsed correctly, you are in a good position to refine the pattern. You will instantly know if a change in pattern has broken another pattern. The reason I'm saying this, is because I think your pattern is incomplete. I suggest you add a test case for the following street address: 221B Baker Street That is a real address in London (only Sherlock Holmes) was fiction. I know it, because I actually visited the location. Can you address matching pattern handle that? Just don't break other address recognition test cases while fixing things. -- http://mail.python.org/mailman/listinfo/python-list
Re: .join(string_generator()) fails to be magic
Matt Mackal [EMAIL PROTECTED] wrote: I have an application that occassionally is called upon to process strings that are a substantial portion of the size of memory. For various reasons, the resultant strings must fit completely in RAM. Do you mean physical RAM, or addressable memory? If the former, there's an obvious solution Occassionally, I need to join some large strings to build some even larger strings. Unfortunately, there's no good way of doing this without using 2x the amount of memory as the result. I think you can get better than 2x if you've got a reasonable number of (ideally similarly sized) large strings with something along the lines of: for i in range(0, len(list_of_strings), 3): #tune step result_string += (list_of_strings[i] + list_of_strings[i+1] + list_of_strings[i+2]) list_of_strings[i] = list_of_strings[i+1] = list_of_strings[i+2] = remembering the recent string concatenation optimisations. Beyond that, your most reliable solution may be the (c)StringIO approach but with a real file (see the tempfile module, if you didn't know about it). -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ Frankly I have no feelings towards penguins one way or the other -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
RE: RMI with Pyro et al
Sells, Fred wrote: Diez B. Roggisch wrote . Why do you want that (hot deploy) anyway? Does startuptime of a script really bother you? shouldn't take more than a few seconds. My primary need is development/debug. I'm a Pyro newbie and I add a feature and then test. The only way I've found to kill the Pyro server on XP is to open the task manager and kill the python task (hopefully the right one). Go install cygwin (but not it's included python-interpreter, or at least make sure you have your python path properly under control) and then simply start the script from the command-line. And hit C-c if you need it to stop, and restart it. Only start it as service if it's deployed. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: PyDev 1.3.9 code compleition trouble
Vyacheslav Maslov wrote: I use Pydev 1.3.9 and notice issue related to code completion. I give an ...stuff deleted... proposed also as well. Why this doesn't work? You will have better luck asking this question on the Pydev forum: http://sourceforge.net/forum/forum.php?forum_id=293649 The SF forum is also mirrored on gmane as: gmane.comp.ide.eclipse.plugins.pydev.user Fabio provides an _amazing_ level of support for Pydev on this forum, I don't think he ever sleeps. Don. -- http://mail.python.org/mailman/listinfo/python-list
Python process automatically restarting itself
What is the best way for a Python process (presumed to be a script run by the interpreter binary, not embedded in some other program) to restart itself? This is what I've been trying: import __main__ for path in sys.path: path += '/' + __main__.__file__ if os.access(path, os.F_OK): break else: raise Exception('WTF?') #Then, something like... os.execl(sys.executable, sys.executable, path, *sys.argv[1:]) BUT! This is a multi-threaded program, and at least on OS X, trying to exec*() in a threaded process raises OSError [Errno 45] Operation not supported. So I tried having it fork, and having the child process wait for the parent process to die (in various ways) and then exec*(). That seemed to work, sort of, but the child would not be attached to the original terminal, which is a must. Any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
Artur Siekielski wrote: On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: But why? Default getters and setters are unnecessary and if you need something other than the default you need to write it anyway more explicitly. I see some problems with your approach: 1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value. In practice, it turns out to be a lot less work to deal with that occasionally than to always deal with lugging around internal attributes and external properties when they're really not needed. By writing everything as properties up front you're just creating more work for yourself, and it's generally considered bad practice in Python to have default getters/setters (whether part of a property or not). 2. Properties define (a part of) public interface of a class. When using fields for public access, you must tell this explicitly in documentation, or use name convention. Property vs. attribute doesn't make any difference here: both of them are public, and part of the external interface, unless they're named with a leading underscore. Making something a property doesn't make it any more or less a part of the public interface. 3. Using properties as first-class objects gives possibilities to use declarative approaches for constructing them. This doesn't make any sense. Properties and attributes are both objects in python. -- http://mail.python.org/mailman/listinfo/python-list
Re: EasyMock for python ?
On 10/10/07, BlueBird [EMAIL PROTECTED] wrote: Does anybody know where to find a library like EasyMock for python ? I searched quickly but could not find anything. I found python-mocks on sourceforge but form quickly reading the docs, it is not an EasyMock style mock. Actually, according to http://martinfowler.com/articles/mocksArentStubs.html I don't think it is even a mock library. More a stub. python-mock is more jMock than EasyMock in style, it's true, and the fact that you define expectations *after* the test invocation rather than before does feel a bit odd. But it does indeed check against the defined expectations, so that makes it a mock library in my book. A record-playback EasyMock style mock library would be nice, it's true... -- Cheers, Simon B. [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues -- http://mail.python.org/mailman/listinfo/python-list
Advice on long running processes
Hello, I write a lot of CGI scripts, in Python of course. Now I need to convert some to long-running processes. I'm having trouble finding resources about the best practices to do that. I've found a lot of email discussions that say something like, You need to educate yourself about the differences when you have long- running processes but I've not had a lot of luck with finding things that explain the differences. I've seen some talk about database timeouts, for instance, but I'm not sure I understand the problems. Can anyone here suggest some resources? I'd be happy with web sites, with buying a book, anything. I ask here because I write in Python and so if those resources used Python then that would be super. Thanks, Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannibals For The Presidency! Meet, The Candidates!
On Thu, 11 Oct 2007 07:10:41 -0700, [EMAIL PROTECTED] wrote: Introducing The Dhourties And The Dualdigers, Nudism? Nakedity? Aren't We Born Naked? Isn't Our Naked Skin Our Clothes? Is Being Born Naked A Crime By The Dhourties' Logic If Nudity In Public Is A Crime? Sanest post I've seen here all year. BTW, it's Morlock, not Warlock. -- Josh Playing 'Bop' is like playing Scrabble with all the vowels missing. - Duke Ellington -- http://mail.python.org/mailman/listinfo/python-list
Re: Advice on long running processes
[EMAIL PROTECTED] wrote: Hello, I write a lot of CGI scripts, in Python of course. Now I need to convert some to long-running processes. I'm having trouble finding resources about the best practices to do that. I've found a lot of email discussions that say something like, You need to educate yourself about the differences when you have long- running processes but I've not had a lot of luck with finding things that explain the differences. The biggest differences between run-and-exit vs. long running processes are resource management and error recovery. Let's take them one at a time. Resource management. In a short-lived process, you really don't have to worry about this at all. Snarf as much memory as you need, open as many files as you want, and when you exit, the operating system cleans it all up for you. With a long running process, you have to worry about stuff like that. In Python, you're isolate from the low-level details of memory management, but still need to think about it a bit. Imagine you had code that looked like this in your main loop: for request in getNextRequest(): requestList.append (request) processRequest(request) requestList is going to keep growing without bounds and eventually will eat up all available memory in the system and your process will crash. Everything you store, you also need to delete when you're done with it. Same with files. In a short-lived process, you can generally open as many files as you want and never worry about closing them. It unlikely you will ever run out of file descriptors. In a long running process, that's not the case. If you open a new file each time you get a request and never close it, after a few hundred requests (depending on the operating system, maybe even a few thousand), you'll run out of file descriptors. The other big thing is error recovery. In a short lived process, if something fails, you print an error message and exit. In a long running process, you need to somehow recover from the error and keep going as best you can. This can be tricky. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python module for making Quicktime or mpeg movies from images
jeremito wrote: My Python script makes a bunch of images that I want to use as frames in a movie. I've tried searching for a module that will take these images and put them together in a Quicktime or mpeg movie, but haven't found anything. My images are currently pdfs, but I could make them into just about anything if needed. Is there a module, or example of how to do this? http://pymedia.org/ Diez -- http://mail.python.org/mailman/listinfo/python-list
Python module for making Quicktime or mpeg movies from images
My Python script makes a bunch of images that I want to use as frames in a movie. I've tried searching for a module that will take these images and put them together in a Quicktime or mpeg movie, but haven't found anything. My images are currently pdfs, but I could make them into just about anything if needed. Is there a module, or example of how to do this? Thanks, Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: Script to Remove Attachments in Exchange Mailbox
KDawg44 wrote: Hi, I am frustrated with my users who send large files around the office instead of using the network shares. [...] Which means that there are 8 copies of the same file 4MB taking up space, or a 4MB file turned into a 32MB file. So, what I would like, is to write a script that parses the exchange mailbox, and removes all attachments over a certain size (say 500K) that are attached to messages that are more than 2 weeks old, or that are in sent items. I would like to write to a log file all the changes that are made then email that log file to the mailbox that was just trimmed. I have something v. similar, only it's at work and I'm not. Maybe tomorrow. What it does -- I think, it's been a while -- is to rip through any mailboxes finding attachments over a certain size, saving them to some kind of folder structure on the user's home drive and replacing the attachment by a link to the attachment. I have another script which, independently, rips through users' home shares finding duplicates and linking them to one copy. It's a while since they were last run to they're probably quite dusty but it sounds like the kind of thing you're after. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: RuntimeWarning: tp_compare
Chris Mellon wrote: On 10/9/07, Bruno Barberi Gnecco [EMAIL PROTECTED] wrote: I'm getting the following exception when I call an external extension (pytst): /usr/lib/python2.5/threading.py:697: RuntimeWarning: tp_compare didn't return -1 or -2 for exception return _active[_get_ident()] Traceback (most recent call last): File testDataMiner2.py, line 77, in module testPlace() File testDataMiner2.py, line 41, in testPlace data = db.getDescription(event['id']) File testDataMiner2.py, line 28, in getDescription return self.getRow(query, (id,)) File ../database.py, line 73, in getRow self.readlock.acquire() File /usr/lib/python2.5/threading.py, line 94, in acquire me = currentThread() File /usr/lib/python2.5/threading.py, line 697, in currentThread return _active[_get_ident()] UnicodeEncodeError: 'ascii' codec can't encode character u'\xfa' in position 52: ordinal not in range(128) awer /usr/lib/python2.5/threading.py(700)currentThread() - return _DummyThread() Note that the error occurs *after* the call that I isolated as affecting it (pytst.scan(), in the case). This doesn't happen for simple, isolated cases, but googling for tp_compare threading shows a lot of similar issues. Does anybody here know what this could be about? Any ideas to debug or work around it? The various thread issues in the traceback aside, it looks like the problem is that you passed a unicode object to pytst, which only accepts plain (ascii) strings. That seems to have solved it. Thanks! -- Bruno Barberi Gnecco brunobg_at_users.sourceforge.net There is no time like the pleasant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python module for making Quicktime or mpeg movies from images
On Oct 11, 10:43 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: jeremito wrote: My Python script makes a bunch of images that I want to use as frames in a movie. I've tried searching for a module that will take these images and put them together in a Quicktime or mpeg movie, but haven't found anything. My images are currently pdfs, but I could make them into just about anything if needed. Is there a module, or example of how to do this? http://pymedia.org/ Diez That initially looked promising, but it looks like nobody is working on it anymore and it doesn't compile on Mac. (I should have mentioned I am using a Mac.) Any other suggestions? Thanks, Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: Advice on long running processes
Roy Smith wrote: [EMAIL PROTECTED] wrote: Hello, I write a lot of CGI scripts, in Python of course. Now I need to convert some to long-running processes. I'm having trouble finding resources about the best practices to do that. I've found a lot of email discussions that say something like, You need to educate yourself about the differences when you have long- running processes but I've not had a lot of luck with finding things that explain the differences. The biggest differences between run-and-exit vs. long running processes are resource management and error recovery. Let's take them one at a time. Resource management. In a short-lived process, you really don't have to worry about this at all. Snarf as much memory as you need, open as many files as you want, and when you exit, the operating system cleans it all up for you. With a long running process, you have to worry about stuff like that. In Python, you're isolate from the low-level details of memory management, but still need to think about it a bit. Imagine you had code that looked like this in your main loop: for request in getNextRequest(): requestList.append (request) processRequest(request) requestList is going to keep growing without bounds and eventually will eat up all available memory in the system and your process will crash. Everything you store, you also need to delete when you're done with it. In particular, it is a good idea to call gc.collect() every now and then, specially if you are in such a loop. I don't know what is the gc policy in python, but an application of mine that seemed to eat as much memory as it was available was reduced to a constant small amount of memory after I started to call the gc directly. The other big thing is error recovery. In a short lived process, if something fails, you print an error message and exit. In a long running process, you need to somehow recover from the error and keep going as best you can. This can be tricky. You should have your main loop inside a try/except, to catch any exceptions that were not otherwise caught without exiting the application. Log the exceptions, of course, but in most long running applications work in a loop like Roy Smith's code above, so if one of them fails it won't disrupt the others to come. -- Bruno Barberi Gnecco brunobg_at_users.sourceforge.net The earth is like a tiny grain of sand, only much, much heavier. -- http://mail.python.org/mailman/listinfo/python-list
where to put application-specific data files?
Hello, I am developing an application that needs some data files, but I am not sure what the best way to package and access them. For instance, I have module like: mymodule/ __init__.py run.py data/ file1.dat file2.dat In run.py, I can do something like: fname='data/file1.dat' which will work if I run it *in* the mymodule folder. Once I install it, or want to do: import mymodule mymodule.run.this() it won't know where the data/ folder is. Is there a recommended way of locating application-specific data files? If I want to save user- configuration files, is there a recommended procedure/place for these? thanks, Brian Blais -- Brian Blais [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Re: Python module for making Quicktime or mpeg movies from images
jeremito wrote: On Oct 11, 10:43 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: jeremito wrote: My Python script makes a bunch of images that I want to use as frames in a movie. I've tried searching for a module that will take these images and put them together in a Quicktime or mpeg movie, but haven't found anything. My images are currently pdfs, but I could make them into just about anything if needed. Is there a module, or example of how to do this? http://pymedia.org/ Diez That initially looked promising, but it looks like nobody is working on it anymore and it doesn't compile on Mac. (I should have mentioned I am using a Mac.) Any other suggestions? Not really a Python module but... run them through mencoder? (Haven't tried it but it seems to be saying it's possible). http://www.mplayerhq.hu/DOCS/man/en/mplayer.1.html#EXAMPLES%20OF%20MENCODER%20USAGE TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH on OS X
On Oct 10, 4:59 pm, Graham Dumpleton [EMAIL PROTECTED] wrote: On Oct 11, 8:00 am, mhearne808[insert-at-sign-here]gmail[insert-dot- here]com [EMAIL PROTECTED] wrote: I'm missing something major here. I'm trying to add a directory to my python path using the PYTHONPATH environment variable, and it's being ignored by the Python interactive shell. Below is a capture of what I did. Note that my newfolder appears nowhere on the list of directories in sys.path. How do I get Python to pay attention to my shell variables? Using bash on OS X 10.4.10. %:~ user$ echo $PYTHONPATH %:~ user$ PYTHONPATH=/Users/user/newfolder %:~ user$ echo $PYTHONPATH /Users/user/newfolder %:~ user$ python Python 2.5.1 (r251:54863, Aug 10 2007, 10:46:58) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type help, copyright, credits or license for more information. import sys sys.path ['', '/usr/local/lib/python2.5/site-packages/ setuptools-0.7a1dev_r56320-py2.5.egg', '/usr/local/lib/python2.5/site- packages/ipython1-0.9alpha2-py2.5.egg', '/usr/local/lib/python2.5/site- packages/SQLAlchemy-0.4.0beta5-py2.5.egg', '/usr/local/lib/python2.5/ site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg', '/usr/ local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/ python2.5/plat-darwin', '/usr/local/lib/python2.5/plat-mac', '/usr/ local/lib/python2.5/plat-mac/lib-scriptpackages', '/usr/local/lib/ python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/ lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/ PIL'] You need to export the environment variable. export PYTHONPATH Graham Thanks all - I'm recently back to using Unix (Mac) after 5 years of being on a PC. I guess I thought export was just another way of doing assignment. My bad. --Mike -- http://mail.python.org/mailman/listinfo/python-list
Finding Peoples' Names in Files
Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On Oct 11, 5:22 pm, brad [EMAIL PROTECTED] wrote: Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. Can't you just use the string function .findall() ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On 11/10/2007, brad [EMAIL PROTECTED] wrote: Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. -- http://mail.python.org/mailman/listinfo/python-list Text = open(fname).read() def a_function(): for Name in ['Guido', Robert',Susan']: if Name in Text: return 1 if a_function(): print A name was found :) -- http://mail.python.org/mailman/listinfo/python-list
a good website for softwares,sports,movies and music ,sex etc.
www.space666.com good -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
[EMAIL PROTECTED] wrote: On Oct 11, 5:22 pm, brad [EMAIL PROTECTED] wrote: Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. Can't you just use the string function .findall() ? I mean *any* possible person's name... I don't *know* the names beforehand :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with struct.pack()
On 10/11/07, Carsten Haese [EMAIL PROTECTED] wrote: This is much clearer, and it explains why you need to mix arbitrary binary data with unicode text. Because of this mixing, as you have surmised, you're going to have to treat the file as a binary file in Python. In other words, don't open the file with the codecs module and do the encoding yourself, like so: mystring = uHello World file = open( somefile.txt, wb ) file.write( struct.pack ( I, len(mystring) ) ) file.write( mystring.encode(utf-16-le) ) (Note that I've guessed that you want little-endian byte-order in the encoding. Without that indication, encode() would put a byte order mark at the beginning of the string, which you probably don't want.) Hope this helps, Carsten. What if 'mystring' has been encoded to utf-8? mystring = uHello World mystring = mystring.encode( utf-8 ) So far the code above doesn't seem to work with this. -- http://mail.python.org/mailman/listinfo/python-list
RE: RMI with Pyro et al -- thanks for help
thanks, that should do it Diez wrote: Go install cygwin (but not it's included python-interpreter, or at least make sure you have your python path properly under control) and then simply start the script from the command-line. And hit C-c if you need it to stop, and restart it. Only start it as service if it's deployed. Diez -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
brad wrote: [EMAIL PROTECTED] wrote: On Oct 11, 5:22 pm, brad [EMAIL PROTECTED] wrote: Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. Can't you just use the string function .findall() ? I mean *any* possible person's name... I don't *know* the names beforehand :) Erm, now what's a persons name then? Maybe there is a Viagra Cialis living in ... Caracas. Or so. Or a Woodshed Ribcage in Oregon... who knows? And what about variable names - peters_temp a name? It's amazing what lack of creativity in variable names can result in... So - unless you come up with positive list of what you consider a name, you're pretty much out of luck. diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On Oct 11, 5:40 pm, brad [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Oct 11, 5:22 pm, brad [EMAIL PROTECTED] wrote: Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. Can't you just use the string function .findall() ? I mean *any* possible person's name... I don't *know* the names beforehand :) Well for something like that you could either do a search for .istitle() through the file with a for loop, but that will catch those after a full stop, or other random entries. Otherwise, you get a HUGE list of all possible names? In dictionary format for best option, and check the file against in using in... However...how can you know it is a name... -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
On Oct 11, 4:21 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: In practice, it turns out to be a lot less work to deal with that occasionally than to always deal with lugging around internal attributes and external properties when they're really not needed. By writing everything as properties up front you're just creating more work for yourself, and it's generally considered bad practice in Python to have default getters/setters (whether part of a property or not). Ok, I appreciate your and Marc's argument. So I see that a pythonic way is using public attributes, and it works in real life. Automatic generation of getters/setters is a nice thing when using Java style of properties, ie. no public fields. 2. Properties define (a part of) public interface of a class. When using fields for public access, you must tell this explicitly in documentation, or use name convention. Property vs. attribute doesn't make any difference here: both of them are public, and part of the external interface, unless they're named with a leading underscore. Nice thing about properites is that they are defined in more declarative way - in class body. Attributes are defined in a piece of code (which can be long and can contain loops etc.) by assigning a value to 'self'. 3. Using properties as first-class objects gives possibilities to use declarative approaches for constructing them. This doesn't make any sense. Properties and attributes are both objects in python. Attribute is an object which has value specific for the time it's get from object. It is separated from containing object - relation to it is lost. Python property is an object that describes how to get/set a specific attribute of containing object - any time. It describes relationship between the two. By declarative method I mean something like a function that takes a property object and returns modified property object: def not_none(prop): def new_fset(self, obj): if obj is not None: prop.fset(self, obj) else: raise 'Cannot set None value' return property(prop.fget, new_fset, prop.fdel) And then: class Person(object): ... name = not_none( property(_get_name, _set_name) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On 10/11/07, brad [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Oct 11, 5:22 pm, brad [EMAIL PROTECTED] wrote: Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. Can't you just use the string function .findall() ? I mean *any* possible person's name... I don't *know* the names beforehand :) I cannot combine some characters dhcmrlchtdj which the divine Library has not foreseen and which in one of its secret tongues do not contain a terrible meaning. No one can articulate a syllable which is not filled with tenderness and fear, which is not, in one of these languages, the powerful name of a god. Jorge Luis Borges, The Library of Babel -- http://mail.python.org/mailman/listinfo/python-list
Re: Script to Remove Attachments in Exchange Mailbox
On Oct 11, 10:03 am, Tim Golden [EMAIL PROTECTED] wrote: KDawg44 wrote: Hi, I am frustrated with my users who send large files around the office instead of using the network shares. [...] Which means that there are 8 copies of the same file 4MB taking up space, or a 4MB file turned into a 32MB file. So, what I would like, is to write a script that parses the exchange mailbox, and removes all attachments over a certain size (say 500K) that are attached to messages that are more than 2 weeks old, or that are in sent items. I would like to write to a log file all the changes that are made then email that log file to the mailbox that was just trimmed. I have something v. similar, only it's at work and I'm not. Maybe tomorrow. What it does -- I think, it's been a while -- is to rip through any mailboxes finding attachments over a certain size, saving them to some kind of folder structure on the user's home drive and replacing the attachment by a link to the attachment. I have another script which, independently, rips through users' home shares finding duplicates and linking them to one copy. It's a while since they were last run to they're probably quite dusty but it sounds like the kind of thing you're after. TJG That sounds great! Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with struct.pack()
On Thu, 2007-10-11 at 10:45 -0500, Robert Dailey wrote: What if 'mystring' has been encoded to utf-8? mystring = uHello World mystring = mystring.encode( utf-8 ) So far the code above doesn't seem to work with this. Why would you encode the string into UTF-8? Didn't you say that your output file has to be encoded in UTF-16? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
[EMAIL PROTECTED] wrote: However...how can you know it is a name... OK, I admitted in my first post that it was a crazy question, but if one could find an answer, one would be onto something. Maybe it's not a 100% answerable question, but I would guess that it is an 80% answerable question... I just don't know how... yet :) Besides admitting that it's a crazy question, I should stop and explain how it would be useful to me at least. Is a credit card number itself valuable? I would think not. One can easily re and luhn check for credit card numbers located in files with a great degree of accuracy, but a number without a name is not very useful to me. So, if one could associate names to luhn checked numbers automatically, then one would be onto something. Or at least say, hey, this file has luhn validated CCs *AND* it seems to have people's names in it as well. Now then, I'd have less to review or perhaps as much as I have now, but I could push the files with numbers and names to the top of the list so that they would be reviewed first. Brad -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm starting to think like a Pythonista
brad wrote: Bjoern Schliessmann wrote: Why use xrange if you convert it to a full list in place? No advantage there. What is the dis-advantage of using xrange over range in this circumstance? Hardly any, but honestly: Converting it to a list manually is more than superfluous. Regards, Björn -- BOFH excuse #284: Electrons on a bender -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem of Readability of Python
Steven Bethard wrote: Actually, your posting just used dicts normally. Kevin is creating a prototype dict with a certain set of keys, and then copying that dict and filling in the keys each time he creates a new instance. It's basically a poor man's OOP. And operatively, IMHO, there is no difference. Regards, Björn -- BOFH excuse #176: vapors from evaporating sticky-note adhesives -- http://mail.python.org/mailman/listinfo/python-list
Re: storing meta data on dictionary keys
[...]In fact, now that I think of it, get_key is probably a bad name for it, get_other_object_with_this_same_key is probably more apt :) Or more precise: get_key_that_was_used_when_value_was_inserted_into_dictionary :-) Or even more precisely: get_key_object_that_was_used_when_the_initial_value_belonging_to_that_key_was_inserted_into_dictionary since rebinding other values to the stored key won't change it: class Str(str): def __repr__(self): return str(self)+': '+self.tag a = Str('foo') a.tag = I'm the first one! b = Str('foo') b.tag = I'm not. d = {} d[a] = 'bar' d[b] = 'spam' d.items()[0] (foo: I'm the first one!, 'spam') -- http://mail.python.org/mailman/listinfo/python-list
Re: Fwd: NUCULAR fielded text searchable indexing
[EMAIL PROTECTED] writes: ...but it looks a little more akin to Solr than to Lucene. ... I'm not sure but I think nucular has aspects of both since it implements both the search engine itself and also provides XML and HTTP interfaces That sounds reasonable. As a test I built an index with 10's of millions of entries using nucular and most queries through CGI processes clocked in in 100's of milliseconds or better -- which is quite acceptable, for many purposes. How many items did each query return? When I refer to large result sets, I mean you often get queries that return 10k items or more (a pretty small number: typing python into google gets almost 30 million hits) and you need to actually examine each item, as opposed to displaying ten at a time or something like that (e.g. you want to present faceted results). So we're back to the perennial topic of parallelism in Python... ...Which is not such a big problem if you rely on disk caching to provide the RAM access and use multiple processes to access the indices. Right, another helpful strategy might be to use a solid state disk: http://www.newegg.com/Product/Product.aspx?Item=N82E16820147021 -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
On Thu, 11 Oct 2007 15:39:29 +, Artur Siekielski wrote: On Oct 11, 4:21 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: 2. Properties define (a part of) public interface of a class. When using fields for public access, you must tell this explicitly in documentation, or use name convention. Property vs. attribute doesn't make any difference here: both of them are public, and part of the external interface, unless they're named with a leading underscore. Nice thing about properites is that they are defined in more declarative way - in class body. Attributes are defined in a piece of code (which can be long and can contain loops etc.) by assigning a value to 'self'. The convention is to bind all attributes in `__init__()`, possibly to `None` if the real value is not available at that time, and document at least the public ones in the class' docstring. Tools like `pylint` check for attributes that are introduced in other methods than `__init__()` and give a warning. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Advice on long running processes
[EMAIL PROTECTED] a écrit : Hello, I write a lot of CGI scripts, in Python of course. Now I need to convert some to long-running processes. I'm having trouble finding resources about the best practices to do that. I've found a lot of email discussions that say something like, You need to educate yourself about the differences when you have long- running processes but I've not had a lot of luck with finding things that explain the differences. I've seen some talk about database timeouts, for instance, but I'm not sure I understand the problems. Can anyone here suggest some resources? I'd be happy with web sites, with buying a book, anything. I ask here because I write in Python and so if those resources used Python then that would be super. As far as I'm concerned, I'd go for one of the available wsgi frameworks. -- http://mail.python.org/mailman/listinfo/python-list
how to get the NT event log properties with OnObjectReady() with python
I'm trying to get a notification from the NT event for any new event using the DispatchWithEvents() function. Everything seems to be working the way I wanted, but I don't know how to get the properties of the event (ie. event type, message, etc.) from the OnObjectReady() callback. class SinkClass(object): def OnObjectReady(self, *args): #self may be the wmi_sink object print OnObjectReady callback ... print self #.TargetInstance.Message print args[0] def OnCompleted(self, *args): print OnCompleted callback... print args #.TargetInstance.Message def OnObjectPut(self, *args): print OnObjectPut callback... def OnProgress(self, *args): print OnProgress callback... wmi = win32com.client.GetObject(winmgmts: {impersonationLevel=impersonate,(security)}!//./root/cimv2) wmi_sink = win32com.client.DispatchWithEvents(WbemScripting.SWbemSink,SinkClass) wmi.ExecNotificationQueryAsync(wmi_sink,SELECT * FROM __InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent') The argument args in the OnObjectReady() seems to be the interface to a com object (may be the event object itself). I want to read the properties (ie. message, eventID, type, etc) of the triggered NT event. Please help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On Oct 11, 9:11 am, brad [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: However...how can you know it is a name... OK, I admitted in my first post that it was a crazy question, but if one could find an answer, one would be onto something. Maybe it's not a 100% answerable question, but I would guess that it is an 80% answerable question... I just don't know how... yet :) Besides admitting that it's a crazy question, I should stop and explain how it would be useful to me at least. Is a credit card number itself valuable? I would think not. One can easily re and luhn check for credit card numbers located in files with a great degree of accuracy, but a number without a name is not very useful to me. So, if one could associate names to luhn checked numbers automatically, then one would be onto something. Or at least say, hey, this file has luhn validated CCs *AND* it seems to have people's names in it as well. Now then, I'd have less to review or perhaps as much as I have now, but I could push the files with numbers and names to the top of the list so that they would be reviewed first. Brad What the hell are you doing? Your post sounds to me like you have a huge amount of stolen, or at the very least misapprehended, data. Now you want to search it for credit card numbers and names so that you can use them. I am not cool with this! This is a public forum about a programming language. What makes you think that anybody in this forum will be cool with that. Perhaps you aren't doing anything illegal, but it sure is coming off that way. If you are doing something illegal I hope you get caught. At the very least, you might want to clarify why you are looking for such capability so that you don't get effectively black-listed (well, by me at least). Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
Artur Siekielski a écrit : Hi. I would like to have declarative properties in Python, ie. something like slots definitions in defclass in Common Lisp. It seems that even Java will have it, using a library ( https://bean-properties.dev.java.net/ ). I know about 'property' function Actually, it's a class. in Python, but it's normal usage isn't declarative, because I have to code imperatively getters and setters: Indeed. What would be the use of a property (AKA computed attribute) if you don't need to do something specific ? class Person(object): def __init__(self, name): self._name = name def _get_name(self): return self._name def _set_name(self, new_name): self._name = new_name name = property(_get_name, _set_name) While it's often seen as demonstration code for a property, it's actually totally useless. If all you want to do is to get and set an attribute (I mean, without any computation anywhere), then just use an attribute - you will always be able to turn it into a property if and whene the need arises. I would like to have something like that: class Person(object): name = property('_name') I assume that this causes generation of instance field '_name' and default getters and setters. So far, it's a waste of time. That's exactly what you'd get with a plain attribute, with far less complexity and overhead. And if I would like to customize (g| s)etters, I would write them by hand, Which bring us back to how properties actually work !-) or, better, use more declarative approach (like @NotNull annotations in Java version). I could probably code a solution to my problem with help of wonderful introspection functionalities. But I'm looking for a standard and/or proven way of doing this. Maybe some PEP is being prepared for this? I guess you want to have a look at the descriptor protocol - it's what makes properties work, and it allow you to write your own custom 'smart attributes'. If you want automatic validation/conversion, you could write custom descriptors working with the FormEncode package (I started such a thing for Elixir, but had no time to finish it so far). It would then looks like: class Person(object): name = StringField(empty=False) // etc HTH -- http://mail.python.org/mailman/listinfo/python-list
how to get the NT event log properties with OnObjectReady() with python
I'm trying to get a notification from the NT event for any new event using the DispatchWithEvents() function. Everything seems to be working the way I wanted, but I don't know how to get the properties of the event (ie. event type, message, etc.) from the OnObjectReady() callback. class SinkClass(object): def OnObjectReady(self, *args): #self may be the wmi_sink object print OnObjectReady callback ... print self #.TargetInstance.Message print args[0] def OnCompleted(self, *args): print OnCompleted callback... print args #.TargetInstance.Message def OnObjectPut(self, *args): print OnObjectPut callback... def OnProgress(self, *args): print OnProgress callback... wmi = win32com.client.GetObject(winmgmts: {impersonationLevel=impersonate,(security)}!//./root/cimv2) wmi_sink = win32com.client.DispatchWithEvents(WbemScripting.SWbemSink,SinkClass) wmi.ExecNotificationQueryAsync(wmi_sink,SELECT * FROM __InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent') The argument args in the OnObjectReady() seems to be the interface to a com object (may be the event object itself). I want to read the properties (ie. message, eventID, type, etc) of the triggered NT event. Please help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On Thu, 11 Oct 2007 11:22:50 -0400, brad wrote: Crazy question, but has anyone attempted this or seen Python code that does? For example, if a text file contained 'Guido' and or 'Robert' and or 'Susan', then we should return True, otherwise return False. It'll be hard to handle the Dweezil's and Moon Unit's of the world (I believe these are Frank Zappa's kids?), but you could compile a list of reasonably common names by gaining access to a usenet news spool, and pulling the names from the headers. But then this is starting to sound dangerously like a spam campaign - in which case, Please don't!. -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
Artur Siekielski a écrit : On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: But why? Default getters and setters are unnecessary and if you need something other than the default you need to write it anyway more explicitly. I see some problems with your approach: 1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). Why so ? class Toto(object): def __iinit__(self, name): self.name = name @apply def name(): def fget(self): print getting %s.name % self return self._name def fset(self, val): print setting %s.name to %s % (self, val) self._name = name def say_hello(self): print Hello, my name is %s % self.name t = Toto('bruno') t.say_hello() The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value. But then, you do know where you want the raw value, don't you ? And this would be for special cases that didn't exist before this refactoring, anyway ? 2. Properties define (a part of) public interface of a class. So do attributes. When using fields for public access, you must tell this explicitly in documentation, or use name convention. And public fields definition is mixed with private fields, which doesn't happen when using properties. I just don't understand what you're saying here. As long as you did not prefix a name with an underscore, it's part of the API. And anyway, nothing (except common sens) will prevent anyone to mess with implementation attributes. 3. Using properties as first-class objects Which they are already - I don't know of anything that isn't a first-class object in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: matching a street address with regular expressions
Andy Cheesman [EMAIL PROTECTED] wrote: Check out kodos http://kodos.sourceforge.net/ for an interactive python regexp tester Andy On systems with tkinter installed(So pretty much all Windows and lots and lots of Linux systems), the redemo.py script in the Tools/Scripts directory of the python installation will be a little quicker to get running. max -- http://mail.python.org/mailman/listinfo/python-list
Parsing a commandline from within Python
Hello, I am writing a commandline tool in Python which is often feed with lots of commandline arguments. In practice, the commandline already reached a critical length which is to long for Windows (some versions of Windows only support commandlines of up to 2047 characters). To work around this problem, we thought up the idea of bypassing the commandline into a file and then letting Python parse the content of the file the same way, the arguments in sys.argv are parsed. Is there any buildin function which mimics the behavior of the standard commandline parser (generating a list of strings foo bar and some text from the commandline foo bar some text)? If not, do you have any other ideas how to handle this problem (increasing commandline length, xml files might be a way)? Regards, Andreas Huesgen Viel oder wenig? Schnell oder langsam? Unbegrenzt surfen + telefonieren ohne Zeit- und Volumenbegrenzung? DAS TOP ANGEBOT FÜR ALLE NEUEINSTEIGER Jetzt bei Arcor: günstig und schnell mit DSL - das All-Inclusive-Paket für clevere Doppel-Sparer, nur 34,95 inkl. DSL- und ISDN-Grundgebühr! http://www.arcor.de/rd/emf-dsl-2 -- http://mail.python.org/mailman/listinfo/python-list
Re: Keeping track of subclasses and instances?
On Oct 11, 2007, at 12:49 AM, Andreas Kraemer wrote: On Oct 10, 6:19 pm, Karlo Lozovina [EMAIL PROTECTED] wrote: Larry Bates wrote: I'm not completely sure I understand the question but here goes. Instances of classes are classes can be stored in lists or dictionaries. In lists you reference them via their index (or iterate over them) and in dictionaries you can give them a name that is used as a key. I wish if it were that simple :). Here is a longer description - I have a function that given input creates a custom class and returns it back. The user is free to subclass that (even more, he should do that), and of course he will make instances of those subclasses. Now, my question is how to keep track of subclasses and their instances, without the need for user interaction (appending them to a list, or adding to dictionary)? Thanks, -- Karlo Lozovina - Mosorclass Meta(type): What about the following solution? class Meta(type): def __new__(mcl,*args,**kw): class_ = super(Meta,mcl).__new__(mcl,*args,**kw) mcl._classes.append(class_) class_._instances = [] return class_ _classes = [] def factory(): class Class(object): __metaclass__ = Meta def __new__(cls,*args,**kw): instance = super(Class,cls).__new__(cls,*args,**kw) cls._instances.append(instance) return instance return Class A = factory() class B(A): pass ... a = A() b = B() Meta._classes [class 'meta.Class', class '__main__.B'] A._instances [meta.Class object at 0xb7dbb08c] B._instances [__main__.B object at 0xb7dbb0ec] So, you see that you can access all classes, their subclasses, and instances from Meta. Of course in a more elaborate version _classes and _instances should store weak references, so that classes and instances can actually be deleted. I also haven't explored under which circumstances this can break ... I can imagine different use cases for this, (though they certainly are non-standard :-)). I once contemplated the (toy-) implementation of a frame-based knowledge representation system using Python's object model, where one definitely needs classes to keep track of their instances ... Another use case that I've run across is when defining model classes using an ORM against a database that uses table inheritance extensively with the result that the database has way more tables than you'd actually want to manually maintain model classes/files for. Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate market in style. Visit us online at http://www.myemma.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On Oct 11, 12:49 pm, Matimus [EMAIL PROTECTED] wrote: On Oct 11, 9:11 am, brad [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: However...how can you know it is a name... OK, I admitted in my first post that it was a crazy question, but if one could find an answer, one would be onto something. Maybe it's not a 100% answerable question, but I would guess that it is an 80% answerable question... I just don't know how... yet :) Besides admitting that it's a crazy question, I should stop and explain how it would be useful to me at least. Is a credit card number itself valuable? I would think not. One can easily re and luhn check for credit card numbers located in files with a great degree of accuracy, but a number without a name is not very useful to me. So, if one could associate names to luhn checked numbers automatically, then one would be onto something. Or at least say, hey, this file has luhn validated CCs *AND* it seems to have people's names in it as well. Now then, I'd have less to review or perhaps as much as I have now, but I could push the files with numbers and names to the top of the list so that they would be reviewed first. Brad What the hell are you doing? Your post sounds to me like you have a huge amount of stolen, or at the very least misapprehended, data. Now you want to search it for credit card numbers and names so that you can use them. I am not cool with this! This is a public forum about a programming language. What makes you think that anybody in this forum will be cool with that. Perhaps you aren't doing anything illegal, but it sure is coming off that way. If you are doing something illegal I hope you get caught. At the very least, you might want to clarify why you are looking for such capability so that you don't get effectively black-listed (well, by me at least). Matt Go have a beer and calm down a bit :) It's a legitimate purpose, although it could (and probably is being used by bad guys right now). My intent, as you can see from the links below, is to catch it before the bad guys do. http://filebox.vt.edu/users/rtilley/public/find_ccns/ http://filebox.vt.edu/users/rtilley/public/find_ssns/ Brad -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
Artur Siekielski a écrit : On Oct 11, 4:21 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: In practice, it turns out to be a lot less work to deal with that occasionally than to always deal with lugging around internal attributes and external properties when they're really not needed. By writing everything as properties up front you're just creating more work for yourself, and it's generally considered bad practice in Python to have default getters/setters (whether part of a property or not). Ok, I appreciate your and Marc's argument. So I see that a pythonic way is using public attributes, and it works in real life. Indeed !-) Automatic generation of getters/setters is a nice thing when using Java style of properties, ie. no public fields. Java doesn't have computed attributes, so you have no other choice if you want to keep your design flexible. For languages that have computed attributes, this is not a problem to use plain attributes until you *really* need to do otherwise. 2. Properties define (a part of) public interface of a class. When using fields for public access, you must tell this explicitly in documentation, or use name convention. Property vs. attribute doesn't make any difference here: both of them are public, and part of the external interface, unless they're named with a leading underscore. Nice thing about properites is that they are defined in more declarative way - in class body. Attributes are defined in a piece of code (which can be long and can contain loops etc.) by assigning a value to 'self'. Usually, all there is to know is readable in the initializer. And I've rarely seen (good) code that defines public attribute elsewehere (i've seen such a thing on a couple occasion, and that's bad coding IMHO). Anyway, since attributes (including methods, class etc...) can be added/replaced/deleted by anyone having access to the object at any point of the program, using properties won't help that much here IMHO. Not that I don't see your point - I also have a taste for declarative APIs and readability - but this is enough to justify the use of properties IMHO. -- http://mail.python.org/mailman/listinfo/python-list
Re: Keeping track of subclasses and instances?
George Sakkis a écrit : (snip) Anyway, here's something to get you started; all a user has to do is derive (directly or indirectly) from InstanceTracker and, if a class C defines __init__, super(C,self).__init__() should be called explicitly: Actually, you don't even need that restriction - just move the tracking code from __init__ to __new__. from collections import deque from weakref import WeakKeyDictionary class InstanceTracker(object): def __new__(cls, *args, **kw): try: all = cls.__dict__['__instances__'] except KeyError: cls.__instances__ = all = WeakKeyDictionary() self = super(InstanceTracker, self).__new__(cls) all[self] = None return self (NB : untested) -- http://mail.python.org/mailman/listinfo/python-list
Re: storing meta data on dictionary keys
On Oct 11, 2007, at 1:36 AM, Andreas Kraemer wrote: On Oct 10, 9:00 pm, Erik Jones [EMAIL PROTECTED] wrote: If you're sure that 1. this use case won't grow and 2. that you'll only be the only person ever using code, then it's your choice of preference. Both of those points are equally important. 1 is a manageability issue in that you are complicating what could be an easy solution for a small gain in convenience -- one that could just as easily be had by encapsulating the management of both dicts in an explicit class or function/method. Let me quote lines 2 through 5 of The Zen of Python (PEP20): Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Using two dicts would be explicit, simple and flat. Your's is none of those. For point 2, if anyone else needs to work with your code they're most likely going to be confused as the implementation is overly complex. I know when I initially read through it I had to read it a couple times to assure myself of what it was doing because I was thinking that it seems that there's more going on than there is, so there must be. Remember, the best solutions are those that not only you can understand, but the next guy/girl/?. You are right, and these are all very valid points. One of the reasons I like Python so much is the philosophy behind it. Nevertheless, everything is relative, so a pattern that seems complex (or unusual) at first may become simple when people get used to it ... I hope, I may be excused. In the organization where I work I am mainly prototyping (more on the scientific/algorithm side) and not required to write maintainable code. The engineers will do that (in Java anyway, sadly ..). Excellent. I'm actually love hackish approaches to things when you can afford to use them and it seems like you're in that situation. The trivial class Str(str): pass in the OP (that already inherits the correct __hash__ and __eq__) serves the same purpose as your Node(object) below, ... True, but you're breaking the intended abstraction of inheriting from str, i.e. the reason you can inherit from str is so that you can specialize strings, not get __has__ and __eq__ for free. You can define those on your own for a reason. Who says that that's the intended abstraction of inheriting from str? I thought that one purpose of inheritance was the reuse of behavior (i.e. methods) (and maybe state) of the superclass. So, my class Str(str): pass behaves like a string in all aspects, except that you can attach some meta data that won't affect that behavior. In fact, I use that pattern quite frequently also for other built-in immutable types, e.g. floats or ints, which allows me to very easily tag numerical data (e.g. as an outlier in a stats application or whatever) without affecting any subsequent code operating on it as long as it only uses its built-in flavor. This is the power of Python's duck typing! No, duck typing and inheritance are two different things. Duck typing is when you implement the same operations as another object or class, whereas with inheritance you get the same implementation as that of the parent class. With duck typing, an object acts like another object in specific contexts. With inheritance, an object is the same general type as another object. You don't want string objects, you want objects that, in a specific case, act like strings but in others, I'm sure, not. How does a concept like string substitution fit with your inherited objects? So, (explicitly:) you want the built-in dict to be a dictionary that also maintains a dictionary of its own key Without knowing the internals, so I may be wrong. But dict must somehow maintain a dictionary of the key objects already. How else could it detect collisions of hash values, when it must use __eq__ to determine equality of the query key object to one of the inserted keys having the same hash value? It also needs to do the same check when overwriting an existing key. If you can, get a copy of Beautiful Code (easily had from Amazon or the likes). It contains an chapter on Python's dictionary implementation. Not likely to happen. Again, you're asking to have one dictionary act as two and that's just confusing. I'm not saying that get_key is a bad idea for (possibly) some use cases, just that what you're actually doing is creating a dictionary wherein the same key can return two different object depending on the retrieval method used and that is NOT what the built-in dict is for. In fact, now that I think of it, get_key is probably a bad name for it, get_other_object_with_this_same_key is probably more apt :) Or more precise: get_key_that_was_used_when_value_was_inserted_into_dictionary :-) I like it! Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps
[Python-SWIG-C++] one question about wrapper interface files
Dear All, I am new to Python and SWIG, and I tried to search the SWIG mailinglist for my specific question, but I did not find it. And for a simple one c++ file, I can handle it successfully. Now I have a small project including several C files, file1.C file2.C file3.C file2.h file3.h , file1.C is the main() entry for my project, and file1.C has the following include statements #include file2.h #include fille3.h So for using SWIG, What should I do? Thanks in advance! Jiangfan Shi -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a commandline from within Python
[EMAIL PROTECTED] wrote: Is there any buildin function which mimics the behavior of the standard commandline parser (generating a list of strings foo bar and some text from the commandline foo bar some text)? Try the shlex module:: import shlex shlex.split('foo bar some text') ['foo bar', 'some text'] STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On Oct 11, 10:02 am, [EMAIL PROTECTED] wrote: On Oct 11, 12:49 pm, Matimus [EMAIL PROTECTED] wrote: On Oct 11, 9:11 am, brad [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: However...how can you know it is a name... OK, I admitted in my first post that it was a crazy question, but if one could find an answer, one would be onto something. Maybe it's not a 100% answerable question, but I would guess that it is an 80% answerable question... I just don't know how... yet :) Besides admitting that it's a crazy question, I should stop and explain how it would be useful to me at least. Is a credit card number itself valuable? I would think not. One can easily re and luhn check for credit card numbers located in files with a great degree of accuracy, but a number without a name is not very useful to me. So, if one could associate names to luhn checked numbers automatically, then one would be onto something. Or at least say, hey, this file has luhn validated CCs *AND* it seems to have people's names in it as well. Now then, I'd have less to review or perhaps as much as I have now, but I could push the files with numbers and names to the top of the list so that they would be reviewed first. Brad What the hell are you doing? Your post sounds to me like you have a huge amount of stolen, or at the very least misapprehended, data. Now you want to search it for credit card numbers and names so that you can use them. I am not cool with this! This is a public forum about a programming language. What makes you think that anybody in this forum will be cool with that. Perhaps you aren't doing anything illegal, but it sure is coming off that way. If you are doing something illegal I hope you get caught. At the very least, you might want to clarify why you are looking for such capability so that you don't get effectively black-listed (well, by me at least). Matt Go have a beer and calm down a bit :) It's a legitimate purpose, although it could (and probably is being used by bad guys right now). My intent, as you can see from the links below, is to catch it before the bad guys do. http://filebox.vt.edu/users/rtilley/public/find_ccns/http://filebox.vt.edu/users/rtilley/public/find_ssns/ Brad Its just past 10:00 am where I am... I know customs vary, but generally beer before lunch is frowned upon :). I know the tone of posts does not carry well over the web, but I was really just trying to point out that your previous post sounded very shady, and at the very least some clarification was in order. I wasn't standing on my desk frothing at the mouth or anything. On to my suggestion. I think you are going to have to use statistical analysis. That is, you won't get something that reliably returns a boolean, but maybe something that says there is a 75% chance that there are names in a given file. You can't know that a given string is or isn't a name, you can only know that it is probably a name based upon how often it is used in that context. Either way this isn't a simple problem to solve, and it probably involves creating a database of words that shows what percentage of the time they are used as names. How such a database is created... that is the hard part. There may be tools out there for such analasys, but that isn't an area I have any experience in. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Fwd: NUCULAR fielded text searchable indexing
regarding http://nucular.sourceforge.net On Oct 11, 12:32 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: How many items did each query return? When I refer to large result sets, I mean you often get queries that return 10k items or more (a pretty small number: typing python into google gets almost 30 million hits) and you need to actually examine each item, as opposed to displaying ten at a time or something like that (e.g. you want to present faceted results). I can't give a detailed report. I think 10k result sets were not unusual or noticably slower. Of the online demos, looking at http://www.xfeedme.com/nucular/gut.py/go?FREETEXT=w (w for web) we get 6294 entries which takes about 500ms on a cold index and about 150ms on a warm index. This is on a very active shared hosting machine. You are right that you might want to use more in-process memory for a really smart, multi-faceted relevance ordering or whatever, but you have to be willing to pay for it in terms of system resources, config/development time, etcetera. If you want cheap and easy, nucular might be good enough, afaik. Regarding the 30 million number -- I bet google does estimations and culling of some kind (not really looking at all 10M). I'm pretty sure of this because in some cases I've looked at all results available and it turned out to be a lot smaller than the estimate on the first page. I'm not interested in really addressing the google size of data set at the moment. http://www.newegg.com/Product/Product.aspx?Item=N82E16820147021 holy rusty metal batman! way-cool! thanks, -- Aaron Watters === less is more -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a commandline from within Python
Is there any buildin function which mimics the behavior of the standard commandline parser (generating a list of strings foo bar and some text from the commandline foo bar some text)? Try the shlex module:: import shlex shlex.split('foo bar some text') ['foo bar', 'some text'] Thanks, that is exactly what i need. Andreas Huesgen -- http://mail.python.org/mailman/listinfo/python-list
Re: .join(string_generator()) fails to be magic
On Oct 11, 2:26 am, Matt Mackal [EMAIL PROTECTED] wrote: I have an application that occassionally is called upon to process strings that are a substantial portion of the size of memory. For various reasons, the resultant strings must fit completely in RAM. Occassionally, I need to join some large strings to build some even larger strings. Do you really need a Python string? Some functions work just fine on mmap or array objects, for example regular expressions: import array import re a = array.array('c','hello, world') a array('c', 'hello, world') m = re.search('llo',a) m _sre.SRE_Match object at 0x009DCB80 m.group(0) array('c', 'llo') I would look to see if there's a way to use an array or mmap instead. If you have an upper bound for the total size, then you can reserve the needed number of bytes. If you really need a Python string, you might have to resort to a C solution. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
On Thu, 11 Oct 2007 13:46:12 +, Marc 'BlackJack' Rintsch wrote: On Thu, 11 Oct 2007 13:04:53 +, Artur Siekielski wrote: On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: But why? Default getters and setters are unnecessary and if you need something other than the default you need to write it anyway more explicitly. I see some problems with your approach: 1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value. So what? Otherwise you carry *always* the baggage of a public property and a private attribute whether you need this or not. At least for me it would be unnecessary in most cases. That baggage of carrying around unneeded methods is something the computer carries for you - IE, no big deal in 99.99% of all cases. The baggage of possibly fixing (AKA generalizing) how your attributes are accessed is something you lug around while your deadline looms. Here's some code that defines such methods for you: #!/usr/bin/env python def gimme_set_get(foo, attribute): lst = [ \ 'def set_%s(self, value):' % attribute, \ ' self._%s = value' % attribute, \ 'def get_%s(self):' % attribute, \ ' return self._%s' % attribute, \ 'foo.set_%s = set_%s' % (attribute, attribute), \ 'foo.get_%s = get_%s' % (attribute, attribute) \ ] s = '\n'.join(lst) code = compile(s, 'string', 'exec') eval(code) class foo: def __init__(self, value): self.public_value = value gimme_set_get(foo, 'via_accessor_method_only') f = foo(1) f.set_via_accessor_method_only(1/9.0) print f.get_via_accessor_method_only() print dir(f) -- http://mail.python.org/mailman/listinfo/python-list
wana watch latest hindi hot videos?
wana watch latest hindi hot videos? than www.yedil.com is the site you are looking for have a nice time with www.yedil.com .Log on now -- http://mail.python.org/mailman/listinfo/python-list
determining fully qualified package class name
Hi List, I am used to the following with Java: import some.package.MyClass; name = MyClass.class.getName(); The value for name will be some.package.MyClass. For Python, I find: from some.package.myclass import MyClass name = MyClass.__name__ The value for name will be MyClass Is there a comparable way to get the fully qualified name (package, module, and class name) in Python? Thanks, Patrick Smith -- View this message in context: http://www.nabble.com/determining-fully-qualified-package---class-name-tf4609111.html#a13161736 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Binary Packages
On Oct 10, 11:53 am, Jim B. Wilson [EMAIL PROTECTED] wrote: On Wed, 10 Oct 2007 14:35:35 +, kyosohma wrote: I am trying to figure out how to build binaries for Python packages and I've done it with MinGW. Apparently, you still can:http://tinyurl.com/yb4bps I had an acquaintance look at that information who has way more experience in compiling extensions than I do. He says: MinGW seems to usually link to msvcrt.dll and the Python distributions link to msvcr71.dll. It might be possible to convince MinGW to use msvcr71.dll by editing the specs config file but I think it will still link to msvcrt.dll in some cases, possibly alongside msvcr71.dll which makes this quite a mess to debug. Does anyone know if this is an issue? Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Python process automatically restarting itself
On Oct 11, 7:17 am, Adam Atlas [EMAIL PROTECTED] wrote: What is the best way for a Python process (presumed to be a script run by the interpreter binary, not embedded in some other program) to restart itself? This is what I've been trying: import __main__ for path in sys.path: path += '/' + __main__.__file__ if os.access(path, os.F_OK): break else: raise Exception('WTF?') #Then, something like... os.execl(sys.executable, sys.executable, path, *sys.argv[1:]) BUT! This is a multi-threaded program, and at least on OS X, trying to exec*() in a threaded process raises OSError [Errno 45] Operation not supported. So I tried having it fork, and having the child process wait for the parent process to die (in various ways) and then exec*(). That seemed to work, sort of, but the child would not be attached to the original terminal, which is a must. Any ideas? sys.path is the search path that Python uses for finding modules, and probably isn't what you wanted. Also, it is bad practice to hard code the file separator. In general you will want to do this: import os.path path = os.path.join(path, filename) which will automatically insert the correct separator for the os you are using. That is moot though, since I think this is a better solution: import os.path, __main__ path = os.path.abspath(__main__.__file__) That isn't really necessary though. In fact, I think restarting the process using exec* is the wrong way to go. I would simply encapsulate my program inside of a function, set a restart flag, return from said function and restart if the flag was set. Something like this: restart = False def main(): # do my stuff if need_to_restart: global restart restart = True #do clean-up (shut down threads, etc.) return retval if __name__ == __main__: retval = main() while restart: restart = False retval = main() sys.exit(retval) I suppose there are reasons that you might want to restart the process. Most of the time you are going to want to do something like what I suggested though. And even in those other cases, you probably want to use the subprocess module instead of an exec* function. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Is hostmonster any good for hosting python?
I should have mentioned, I am thinking about using a python framework, either django, turbogears, or pylons. I think these frameworks require a newer version of python, maybe 2.4. Also, I think some of them require a newer version of Apache - 2.0 or better. I also think these python frameworks all work with fastcgi, which - I think - is possible with hostmonster. Although fastcgi is acceptable, it is generally not the preferred solution. I do not think you will get reasonable performance with CGI, even if factcgi/mod_python/wsgi are not officially required. Also, I doubt you will find mod_python on any standard shared hosting. To get mod_python you will need 1) a host that speciallizes in python - like webfaction. 2) a virtual host 3) something like hcoop.net, which may be sort-of like a virtual host. BTW: hccoop.net has a long-running freeze on new memberships. Please correct me if I'm wrong about any of this. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I make urllib2 preserve case in HTTP header names?
[EMAIL PROTECTED] writes: The HTTP specification, RFC 2616, states that field names in HTTP headers are case insensitive. But I'm trying to use Python 2.5.1's urllib2 to interact with a web service offered by Amazon.com, which deviates from the HTTP spec in that it requires use of case-sensitive header names ReportName, ReportID, and NumberOfReports. I try to send an HTTP header named NumberOfReports, but it comes out mangled as Numberofreports'. What is the best way to use Python 2.5.1 on Windows Server 2003 to create HTTP or HTTPS requests that do not mangle the case of header field names? httplib John -- http://mail.python.org/mailman/listinfo/python-list
problem with wxPanel derivation class
wxGlade created a simple Frame with a panel a sizer and 3 wxControls , saticText, TextCtrl, and a Button. The resulting code works fine. Now the problem. I wish to make a separate class derrived from wxPanel that has the sized and controls as above. It jusst won't work code id=gladeGen class=works_ok #!/usr/bin/env python # -*- coding: ISO-8859-1 -*- # generated by wxGlade 0.4cvs on Thu Oct 11 13:26:19 2007 import wx class MyFrameOne(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrameOne.__init__ kwds[style] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.panel = wx.Panel(self, -1) self.staticbox = wx.StaticBox(self.panel, -1, StaticBox) self.label = wx.StaticText(self.panel, -1, Field Name) self.textBox = wx.TextCtrl(self.panel, -1, Field Value) self.button = wx.Button(self.panel, -1, Edit) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrameOne.__set_properties self.SetTitle(frame_1) self.label.SetMinSize((-1, 15)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrameOne.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) sizer.Add(self.label, 0, wx.ALL, 3) sizer.Add(self.textBox, 0, wx.ALL, 3) sizer.Add(self.button, 0, wx.ALL, 3) self.panel.SetAutoLayout(True) self.panel.SetSizer(sizer) sizer.Fit(self.panel) sizer.SetSizeHints(self.panel) sizer_1.Add(self.panel, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) sizer_1.Fit(self) sizer_1.SetSizeHints(self) self.Layout() # end wxGlade # end of class MyFrameOne ## modified from BoaApp class App(wx.App): def OnInit(self): wx.InitAllImageHandlers() self.main = MyFrameOne(None) self.main.Show() self.SetTopWindow(self.main) return True def main(): application = App(0) application.MainLoop() if __name__ == '__main__': main() /code code id=modifiedFromGlade class=fails #!/usr/bin/env python # -*- coding: ISO-8859-1 -*- #The commented out code from MyFrame was moved to class Panel \ # and appropriately modified by changing self.panel to self etc import wx class MyFrameTwo(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrameTwo.__init__ kwds[style] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) ## self.panel = panel(self, -1) self.panel = Panel(self, -1) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrameTwo.__set_properties self.SetTitle(frame_1) self.label.SetMinSize((-1, 15)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrameTwo.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) ## sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) ## sizer.Add(self.label, 0, wx.ALL, 3) ## sizer.Add(self.textBox, 0, wx.ALL, 3) ## sizer.Add(self.button, 0, wx.ALL, 3) self.panel.SetAutoLayout(True) ## self.panel.SetSizer(sizer) ## sizer.Fit(self.panel) ## sizer.SetSizeHints(self.panel) sizer_1.Add(self.panel, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) sizer_1.Fit(self) sizer_1.SetSizeHints(self) self.Layout() # end wxGlade # end of class MyFrameTwo class Panel (wx.Panel): def __init__(self, *args, **kwds): self.staticbox = wx.StaticBox(self, -1, StaticBox) self.label = wx.StaticText(self, -1, Field Name) self.textBox = wx.TextCtrl(self, -1, Field Value) self.button = wx.Button(self, -1, Edit) __doLayout() def __doLayout(): sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) sizer.Add(self.label, 0, wx.ALL, 3) sizer.Add(self.textBox, 0, wx.ALL, 3) sizer.Add(self.button, 0, wx.ALL, 3) # maybe comment this and uncommennt frame2's corresponding line panel.SetAutoLayout(True) self.SetSizer(sizer) sizer.Fit(self.panel) sizer.SetSizeHints(self.panel) ## modified from BoaApp class App(wx.App): def OnInit(self):
Re: Declarative properties
On Thu, 11 Oct 2007 09:58:48 -0700, Dan Stromberg wrote: On Thu, 11 Oct 2007 13:46:12 +, Marc 'BlackJack' Rintsch wrote: On Thu, 11 Oct 2007 13:04:53 +, Artur Siekielski wrote: 1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value. So what? Otherwise you carry *always* the baggage of a public property and a private attribute whether you need this or not. At least for me it would be unnecessary in most cases. That baggage of carrying around unneeded methods is something the computer carries for you - IE, no big deal in 99.99% of all cases. It shows twice as much attributes if I inspect the objects and I don't know which are merely useless default getters and setters. And it is more and more complex code. Code can be cut down a bit by some metaclass magic but this brings in another complexity. The baggage of possibly fixing (AKA generalizing) how your attributes are accessed is something you lug around while your deadline looms. Sorry I don't get it. If I want to customize the access to a normal attribute I simply turn it into a property. Here's some code that defines such methods for you: #!/usr/bin/env python def gimme_set_get(foo, attribute): lst = [ \ 'def set_%s(self, value):' % attribute, \ ' self._%s = value' % attribute, \ 'def get_%s(self):' % attribute, \ ' return self._%s' % attribute, \ 'foo.set_%s = set_%s' % (attribute, attribute), \ 'foo.get_%s = get_%s' % (attribute, attribute) \ ] s = '\n'.join(lst) code = compile(s, 'string', 'exec') eval(code) class foo: def __init__(self, value): self.public_value = value gimme_set_get(foo, 'via_accessor_method_only') f = foo(1) f.set_via_accessor_method_only(1/9.0) print f.get_via_accessor_method_only() print dir(f) And the benefit of this evil ``eval`` dance is exactly what!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: determining fully qualified package class name
On Thu, 11 Oct 2007 11:18:33 -0700, patrimith wrote: I am used to the following with Java: import some.package.MyClass; name = MyClass.class.getName(); The value for name will be some.package.MyClass. For Python, I find: from some.package.myclass import MyClass name = MyClass.__name__ The value for name will be MyClass Is there a comparable way to get the fully qualified name (package, module, and class name) in Python? Take a look at the `__module__` attribute of the class. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Pyro: ActiveState (wind32) to Unix
I'm using ActiveState python on a windows box to talk to ACtive Directory. I'm running a Pyro Server on the same box. The client is Linux running std Python 2.4. It works just fine until the server codes calls some win32com.client api; then I get Traceback (most recent call last): File C:\All\projects\AccAdminTools\src\demo002\client\client.py, line 25, in ? unittest() File C:\All\projects\AccAdminTools\src\demo002\client\client.py, line 21, in unittest properties = ad.getProperties() File c:\all\tools\python24\lib\site-packages\Pyro-3.7-py2.4-win32.egg\Pyro\core.py, line 390, in __call__ return self.__send(self.__name, args, kwargs) File c:\all\tools\python24\lib\site-packages\Pyro-3.7-py2.4-win32.egg\Pyro\core.py, line 468, in _invokePYRO return self.adapter.remoteInvocation(name, constants.RIF_VarargsAndKeywords, vargs, kargs) File c:\all\tools\python24\lib\site-packages\Pyro-3.7-py2.4-win32.egg\Pyro\protocol.py, line 416, in remoteInvocation answer = pickle.loads(answer) ImportError: No module named pywintypes the offending code is def getProperties(self): def getProperties(self): attr_dict={} adobj=win32com.client.GetObject(self.LdapPath) #this line causes the error return {'aaa':'bbb'} -- http://mail.python.org/mailman/listinfo/python-list
Re: matching a street address with regular expressions
Don't forget to write test cases. If you have a series of addresses, and confirm they are parsed correctly, you are in a good position to refine the pattern. You will instantly know if a change in pattern has broken another pattern. The reason I'm saying this, is because I think your pattern is incomplete. I suggest you add a test case for the following street address: 221B Baker Street There are a number of weird street names and addresses that one may need to address. Having worked with police applications, they often break it into the BLOCK, DIRECTION, STREET, SUFFIX and APARTMENT/SUITE. However, there are complications... Block can include things like 1234 1/2 (an actual street format from one of our test cases where two block numbers were divided to make room) 221B (though this might be a block + apartment) Directions can include not only your cardinal N/S/E/W directions (written out or abbreviated, with or without punctuation), but can include 8-point directions or more, such as NW, Northwest, north-west, etc. It wouldn't even surprise me if locations with 16-point directions exist (NNW). The Street portion is often whatever is left over when the rest is unparsed. The Suffix would be Rd, Road, St, Ave, Cir, Bvd, Blvd, Row, Hwy, Highway, etc. There are about 30 of them that we used by default, but I'm sure there are some abnormals as well. There are wrinkles in even the above, as here in the Dallas area, we have a Northwest Highway where Northwest is the street-name of the road, not the Direction portion. I second Goldfish's suggestion for making a suite of both normal and abnormal addresses along with their expected breakdowns. Depending on how normalized you want them to be, you may have to deal with punctuation and spacing abnormalities as well. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.ProxyHandler HTTPS issues
Devraj [EMAIL PROTECTED] writes: Hi everyone, I have been reading various documents/posts on the web about handling proxy options in urllib2. Some of them suggest that urllib2 doesn't handle HTTPS and others say it does. I have successfully written code that relays HTTP connections via a proxy but have failed to do the same for HTTPS connections. urllib2 does not support HTTPS proxies (it does not support use of the CONNECT method). Can anyone confirm if urllib2 can handle HTTPS, Yes, it can. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Is hostmonster any good for hosting python?
I should have mentioned, I am thinking about using a python framework, either django, turbogears, or pylons. I think these frameworks require a newer version of python, maybe 2.4. I can't speak for the others, but I know Django can be deployed with 2.3+ (though they offer some nicities if using 2.4). Also, I think some of them require a newer version of Apache - 2.0 or mod_python requires Apache 2.x so if you're deploying with mod_python, yes. However, if you deploy with lighty+fastcgi, it's moot what version of Apache you have. :) better. I also think these python frameworks all work with fastcgi, which - I think - is possible with hostmonster. Although fastcgi is acceptable, it is generally not the preferred solution. The preferred Django deployment environments are - Apache + mod_python - Apache + FastCGI - lighttpd + FastCGI I do not think you will get reasonable performance with CGI, even if factcgi/mod_python/wsgi are not officially required. No...with plain-ol'-CGI, performance is abysmal...the entire framework would be reloaded for each request. Possibly feasible for development if you're patient and have nothing better, but CGI is a generally bad idea. Also, I doubt you will find mod_python on any standard shared hosting. To get a python-framework environment, you usually have to get a better hosting service as the need for mod_python or fastcgi limits you to these hosting services. That means no bottom-of-the-barrel priced hosting services (which usually just offer static pages, basic CGI, or PHP). If one *must* use python in a CGI environment, I'll plug WebStack (the author lurks here on c.l.p, IIRC) which does a nice job of abstracting deployment environments so you can deploy to a variety of targets with minimal fuss. I have several projects in the wild that use WebStack, before I found Django. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Library for crawling forums
I'm trying to write a utility to crawl forums and strip posts to be gone through offline. Just the content, I don't need to get who posted or sigs or any identifying info. Can anyone suggest a library that is already geared toward this? -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
Bruno Desthuilliers wrote: Mathias Panzenboeck a écrit : About the lost weakref problem: in Python, methods are just tiny wrappers around the object, class and function created at lookup time (yes, on *each* lookup) (and WWAI, they are by the function object itself, which implements the descriptor protocol). When I change the class Wrapper to following, the class Foo works: class Wrapper(object): def __init__(self,x): self.func_name = x.func_name self.x = weakref.ref(x.im_self) def __call__(self,*args,**kwargs): x = self.x() if x is None: print lost reference else: return getattr(x,self.func_name)(*args,**kwargs) Anyway, the whole thing looks quite baroque to me - and I'm known for my immoderate appetite for brain-melting features If I understand correctly, you're doing all this to avoid circular references while keeping track of a list of methods to call ? If yes, then you're thru much pain for nothing. Mostly because there are other much more simpler solutions. The first one is obviously to use names and getattr. In it's most naïve implementation, this would look like: class Foo(object): def __init__(self): self._methods = set() self._methods.add('_foo') def _foo(self): print _foo def callMethods(self): for name in self._methods: meth = getattr(self, name, None) if callable(meth): meth() Now if _methods is supposed to have the same content class-wise (which is the case in your exemple), no need to have it as an instance method: class Foo(object): _methods = set('_foo') def _foo(self): print _foo def callMethods(self): for name in self._methods: meth = getattr(self, name, None) if callable(meth): meth() We could go further, like using a decorator to mark methods to add to _methods, and a metaclass to set the whole thing up, but this would probably be overkill. Unless there are other requirements, I'd personnaly stop here. Oh, and yes, while we're at it : Python usually knows how to deal with circular references Well yes and no. It does with the enabled gc but I like refcounting much more because of the predictable behaviour. And when there are no refloops, refcounting makes no problems. However, Alex Martelli already showed a great way to do what I need, see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81253 I need it for a little UI lib. Well lib is too much. Just a small wrapper around blenders unusable API for building GUIs for your scripts. It's ugly as hell. I made very few classes to wrap up that crap. Every input widget in my UI lib has an action. You can register action listeners like this: def actionListener(value): print new value:,value widget.addActionListener(actionListener) When an widget itself want's to listen for it's action and does this in __init__: self.addActionListener(sefl.__actionListener) there would be a ref loop. Therefore I do this now: self.addActionListener(WeakListener(sefl.__actionListener)) And WeakListener I implemented as follows: class WeakListener(object): __slots__ = ('__weakref__', '_func','_obj') def __init__(self,listener): self._func = listener.im_func self._obj = weakref.ref(listener.im_self) def __call__(self,*args,**kwargs): obj = self._obj() if obj is None: print *** lost reference to %s's self object *** % \ self._func.func_name else: self._func(obj,*args,**kwargs) Could be better/more generic, but that's all I need. To implement the action listener by overloading a action method is IMHO a bad idea. Because that would kill the listener of the base class. Explicitly calling the base classes action method is ugly and error prone. And when I have to register action listeners from outside the widget, too. But thanks for your reply. :) -panzi -- http://mail.python.org/mailman/listinfo/python-list
Re: Declarative properties
On Oct 11, 7:42 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: Sorry I don't get it. If I want to customize the access to a normal attribute I simply turn it into a property. I *think* I understand Artur's problem: he wants to be able to add (for example) clean-up and validation code to public accesses of these attributes, but he doesn't want this code run internally to the class. Or another way of saying the same thing: he wants two views of a variable; one internal to the class, another to the public. If I understand correctly, his plan is to use 'X._name' internally to code in his class, but the public uses 'X.name'. Initially, one is an alias for the other, but later he writes getters and setters to customise access through the public version. [I could be totally wrong of course] -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with wxPanel derivation class
none wrote: wxGlade created a simple Frame with a panel a sizer and 3 wxControls , saticText, TextCtrl, and a Button. The resulting code works fine. Now the problem. I wish to make a separate class derrived from wxPanel that has the sized and controls as above. It jusst won't work code id=gladeGen class=works_ok #!/usr/bin/env python # -*- coding: ISO-8859-1 -*- # generated by wxGlade 0.4cvs on Thu Oct 11 13:26:19 2007 import wx class MyFrameOne(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrameOne.__init__ kwds[style] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.panel = wx.Panel(self, -1) self.staticbox = wx.StaticBox(self.panel, -1, StaticBox) self.label = wx.StaticText(self.panel, -1, Field Name) self.textBox = wx.TextCtrl(self.panel, -1, Field Value) self.button = wx.Button(self.panel, -1, Edit) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrameOne.__set_properties self.SetTitle(frame_1) self.label.SetMinSize((-1, 15)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrameOne.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) sizer.Add(self.label, 0, wx.ALL, 3) sizer.Add(self.textBox, 0, wx.ALL, 3) sizer.Add(self.button, 0, wx.ALL, 3) self.panel.SetAutoLayout(True) self.panel.SetSizer(sizer) sizer.Fit(self.panel) sizer.SetSizeHints(self.panel) sizer_1.Add(self.panel, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) sizer_1.Fit(self) sizer_1.SetSizeHints(self) self.Layout() # end wxGlade # end of class MyFrameOne ## modified from BoaApp class App(wx.App): def OnInit(self): wx.InitAllImageHandlers() self.main = MyFrameOne(None) self.main.Show() self.SetTopWindow(self.main) return True def main(): application = App(0) application.MainLoop() if __name__ == '__main__': main() /code code id=modifiedFromGlade class=fails #!/usr/bin/env python # -*- coding: ISO-8859-1 -*- #The commented out code from MyFrame was moved to class Panel \ # and appropriately modified by changing self.panel to self etc import wx class MyFrameTwo(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrameTwo.__init__ kwds[style] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) ##self.panel = panel(self, -1) self.panel = Panel(self, -1) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrameTwo.__set_properties self.SetTitle(frame_1) self.label.SetMinSize((-1, 15)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrameTwo.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) ##sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) ##sizer.Add(self.label, 0, wx.ALL, 3) ##sizer.Add(self.textBox, 0, wx.ALL, 3) ##sizer.Add(self.button, 0, wx.ALL, 3) self.panel.SetAutoLayout(True) ##self.panel.SetSizer(sizer) ##sizer.Fit(self.panel) ##sizer.SetSizeHints(self.panel) sizer_1.Add(self.panel, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) sizer_1.Fit(self) sizer_1.SetSizeHints(self) self.Layout() # end wxGlade # end of class MyFrameTwo class Panel (wx.Panel): def __init__(self, *args, **kwds): self.staticbox = wx.StaticBox(self, -1, StaticBox) self.label = wx.StaticText(self, -1, Field Name) self.textBox = wx.TextCtrl(self, -1, Field Value) self.button = wx.Button(self, -1, Edit) __doLayout() def __doLayout(): sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) sizer.Add(self.label, 0, wx.ALL, 3) sizer.Add(self.textBox, 0, wx.ALL, 3) sizer.Add(self.button, 0, wx.ALL, 3) # maybe comment this and uncommennt frame2's corresponding line panel.SetAutoLayout(True) self.SetSizer(sizer) sizer.Fit(self.panel) sizer.SetSizeHints(self.panel) ## modified from BoaApp class App(wx.App): def
Re: Declarative properties
On Oct 11, 12:48 pm, Artur Siekielski [EMAIL PROTECTED] wrote: Hi. I would like to have declarative properties in Python, ie. something like slots definitions in defclass in Common Lisp. It seems that even Java will have it, using a library (https://bean-properties.dev.java.net/ ). I know about 'property' function in Python, but it's normal usage isn't declarative, because I have to code imperatively getters and setters: class Person(object): def __init__(self, name): self._name = name def _get_name(self): return self._name def _set_name(self, new_name): self._name = new_name name = property(_get_name, _set_name) I would like to have something like that: class Person(object): name = property('_name') Here's something that does what I think you want. I think your use case is quite unusual in that you expect the public accessors to change (keeping private use the same), and that you know you're going to have a costly rewrite of your class when that happens. Attributes that are declared with 'magic_attribute' access the private attribute '_name', unless there's a '_get_name' or '_set_name' method in which case those are called instead. def magic_attribute(_name): def set(self, value): try: getattr(self, '_set' + _name)(value) except AttributeError: setattr(self, _name, value) def get(self): try: return getattr(self, '_get' + _name)() except AttributeError: return getattr(self, _name) return property(get, set) # An example use... class C(object): x = magic_attribute('_x') y = magic_attribute('_y') # Override the default set method for x def _set_x(self, value): self._x = value + ' world' # Override the default get method for y def _get_y(self): return self._y.upper() # Test it works... c = C() c.x = c.y = 'hello' print c.x print c.y # hello world # HELLO -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list