Re: Dynamical loading of modules
On Mon, 2005-10-03 at 15:52, Jacob Kroon wrote: > Hi, I'm having some problems with implementing dynamical module loading. > First let me > describe the scenario with an example: > > modules/ > fruit/ > __init__.py > apple.py > banana.py > > apple.py defines a class 'Apple', banana defines a class 'Banana'. The > problem lies in the > fact that I want to be able to just drop a new .py-file, for instance > peach.py, and not change > __init__.py, and it should automatically pickup the new file in > __init__.py. I've come halfway > by using some imp module magic in __init__.py, but the problem I have is > that the instantiated > objects class-names becomes fruit.apple.Apple/fruit.banana.Banana, whild > I want it to be > fruit.Apple/fruit.Banana. > > Is there a smarter way of accomplishing what I am trying to do ? > If someone could give me a small example of how to achieve this I would > be very grateful. How about something like this in fruit/__init__.py: import os fruit_dir = os.path.dirname(__file__) fruit_files = [x for x in os.listdir(fruit_dir) if (x[-3:]=='.py' and x!='__init__.py')] for fruit_file in fruit_files: module_name = fruit_files[:-3] exec "from %s import *" % module_name HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamical loading of modules
On Mon, 2005-10-03 at 16:41, Carsten Haese wrote: > On Mon, 2005-10-03 at 15:52, Jacob Kroon wrote: > > Hi, I'm having some problems with implementing dynamical module loading. > > First let me > > describe the scenario with an example: > > > > modules/ > > fruit/ > > __init__.py > > apple.py > > banana.py > > > > apple.py defines a class 'Apple', banana defines a class 'Banana'. The > > problem lies in the > > fact that I want to be able to just drop a new .py-file, for instance > > peach.py, and not change > > __init__.py, and it should automatically pickup the new file in > > __init__.py. I've come halfway > > by using some imp module magic in __init__.py, but the problem I have is > > that the instantiated > > objects class-names becomes fruit.apple.Apple/fruit.banana.Banana, whild > > I want it to be > > fruit.Apple/fruit.Banana. > > > > Is there a smarter way of accomplishing what I am trying to do ? > > If someone could give me a small example of how to achieve this I would > > be very grateful. > > How about something like this in fruit/__init__.py: > > import os > > fruit_dir = os.path.dirname(__file__) > fruit_files = [x for x in os.listdir(fruit_dir) if (x[-3:]=='.py' and > x!='__init__.py')] > for fruit_file in fruit_files: > module_name = fruit_files[:-3] ^^^ This should be fruit_file, of course. > exec "from %s import *" % module_name > > HTH, > > Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamical loading of modules
On Mon, 2005-10-03 at 17:37, Steve Holden wrote: > Carsten Haese wrote: > > On Mon, 2005-10-03 at 16:41, Carsten Haese wrote: > > > >>On Mon, 2005-10-03 at 15:52, Jacob Kroon wrote: > >> > >>>Hi, I'm having some problems with implementing dynamical module loading. > >>>First let me > >>>describe the scenario with an example: > >>> > >>>modules/ > >>>fruit/ > >>>__init__.py > >>>apple.py > >>>banana.py > >>> > >>>apple.py defines a class 'Apple', banana defines a class 'Banana'. The > >>>problem lies in the > >>>fact that I want to be able to just drop a new .py-file, for instance > >>>peach.py, and not change > >>>__init__.py, and it should automatically pickup the new file in > >>>__init__.py. I've come halfway > >>>by using some imp module magic in __init__.py, but the problem I have is > >>>that the instantiated > >>>objects class-names becomes fruit.apple.Apple/fruit.banana.Banana, whild > >>>I want it to be > >>>fruit.Apple/fruit.Banana. > >>> > >>>Is there a smarter way of accomplishing what I am trying to do ? > >>>If someone could give me a small example of how to achieve this I would > >>>be very grateful. > >> > >>How about something like this in fruit/__init__.py: > >> > >>import os > >> > >>fruit_dir = os.path.dirname(__file__) > >>fruit_files = [x for x in os.listdir(fruit_dir) if (x[-3:]=='.py' and > >>x!='__init__.py')] > >>for fruit_file in fruit_files: > >> module_name = fruit_files[:-3] > > > > ^^^ This should be fruit_file, of course. > > > > > >> exec "from %s import *" % module_name > >> > > Wouldn't > > __import__(module_name) > > be better. I don't see how a working example that meets the OP's requirements can be constructed using __import__, but that may easily be due to my lack of imagination. How would you do it? Regards, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamical loading of modules
On Tue, 2005-10-04 at 08:32, Steve Holden wrote: > Carsten Haese wrote: > > On Mon, 2005-10-03 at 17:37, Steve Holden wrote: > > > >>Carsten Haese wrote: > >> > >>>On Mon, 2005-10-03 at 16:41, Carsten Haese wrote: > >>> > >>> > >>>>On Mon, 2005-10-03 at 15:52, Jacob Kroon wrote: > >>>> > >>>> > >>>>>Hi, I'm having some problems with implementing dynamical module loading. > >>>>>First let me > >>>>>describe the scenario with an example: > >>>>> > >>>>>modules/ > >>>>> fruit/ > >>>>> __init__.py > >>>>> apple.py > >>>>> banana.py > >>>>> > >>>>>apple.py defines a class 'Apple', banana defines a class 'Banana'. The > >>>>>problem lies in the > >>>>>fact that I want to be able to just drop a new .py-file, for instance > >>>>>peach.py, and not change > >>>>>__init__.py, and it should automatically pickup the new file in > >>>>>__init__.py. I've come halfway > >>>>>by using some imp module magic in __init__.py, but the problem I have is > >>>>>that the instantiated > >>>>>objects class-names becomes fruit.apple.Apple/fruit.banana.Banana, whild > >>>>>I want it to be > >>>>>fruit.Apple/fruit.Banana. > >>>>> > >>>>>Is there a smarter way of accomplishing what I am trying to do ? > >>>>>If someone could give me a small example of how to achieve this I would > >>>>>be very grateful. > >>>> > >>>>How about something like this in fruit/__init__.py: > >>>> > >>>>import os > >>>> > >>>>fruit_dir = os.path.dirname(__file__) > >>>>fruit_files = [x for x in os.listdir(fruit_dir) if (x[-3:]=='.py' and > >>>>x!='__init__.py')] > >>>>for fruit_file in fruit_files: > >>>> module_name = fruit_files[:-3] > >>> > >>> ^^^ This should be fruit_file, of course. > >>> > >>> > >>> > >>>> exec "from %s import *" % module_name > >>>> > >> > >>Wouldn't > >> > >> __import__(module_name) > >> > >>be better. > > > > > > I don't see how a working example that meets the OP's requirements can > > be constructed using __import__, but that may easily be due to my lack > > of imagination. How would you do it? > > > I was simply suggesting that you replace the exec statement with a call > to __import__(). Wouldn't that work? Not the way I tried it by simply replacing my line with your line. (If it matters, I'm on python 2.2 here.) First of all, the __import__ variant doesn't see the submodules unless I add fruit_dir to sys.path. Secondly, the OP's requirements are that the classes that the submodules implement be imported into fruit's namespace, and I don't see how to make __import__ do that. Regards, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python interpreter bug
On Fri, 2005-10-07 at 10:33, [EMAIL PROTECTED] wrote: > In fact, i want to sort the list based on the 'allocated attribute' and > at the same time, test membership based on the id attribute. > __cmp__ logically implies an ordering test, not an identity test. These > two notions seems to be confounded in python which is unfortunate. Two > objects could have the same rank while still being different. > Alain You could use the id in __cmp__ as a tie-breaker if the two objects have equal "allocated" values. By the way, __cmp__ is not an identity test. The "in" operator doesn't use object identity, it uses object equality, and __cmp__ does serve to test object equality (if no __eq__ method is present). Perhaps the following example will clarify the behavior of "in": >>> A = [1] >>> B = [1] >>> A==B True >>> A is B False >>> A in ["spam", 42, B] True HTH, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help creating extension for C function
On Tue, 2005-10-11 at 15:14, Java and Swing wrote: > Anyhow, I need PyBuildValue to work. Try Py_BuildValue. HTH, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Python API InformixDB-2.0 released
Hi everybody, Thanks to significant code contributions by Daniel Smertnig, I am proud to announce release 2.0 of the Informix implementation of the Python DB-API, a mere 5 weeks after release 1.5. Downloads and info at http://informixdb.sourceforge.net/ This release features the following improvements over InformixDB-1.5: * Full compliance with version 2 of the DB-API specification, including many useful optional features suggested by the specification. * Improved documentation: Command line help and HTML manual. * Improved portability: The module now builds painlessly on Windows, and a binary installer for Python 2.4 is provided. Note that this release requires Python 2.2 or better, and it breaks backwards compatibility with version 1 of the DB-API specification. If either of these are a problem for you, you may still use InformixDB-1.5, but I strongly recommend upgrading as I won't develop InformixDB-1.5 any further. Best regards, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: syntax question - if 1:print 'a';else:print 'b'
On Thu, 2005-10-27 at 14:00, Gregory Piñero wrote: > Not quite because if something(3) fails, I still want something(4) to > run. def something_ignore_exceptions(x): try: something(x) except: pass something_ignore_exceptions(1) something_ignore_exceptions(2) # etc... HTH, Carsten Haese -- http://mail.python.org/mailman/listinfo/python-list
Re: Function returns none
On Mon, 2005-10-31 at 14:12, [EMAIL PROTECTED] wrote: > I'm trying to write a website updating script, but when I run the > script, my function to search the DOM tree returns None instead of what > it should. > > I have this program: > > import sys > from xml.dom.minidom import parse > > > # search the tree for an element with a particular class > > def findelement(current, classtofind, topnode = None): > if topnode == None: topnode = current > > > > # if it's an xml element... > if current.nodeType == 1: > print current.nodeName, ':', current.getAttribute('class') > if current.getAttribute('class') == classtofind: > print 'Returning node:', current > return current > elif current.hasChildNodes(): > findelement(current.firstChild, classtofind, topnode) > elif current.nextSibling: > findelement(current.nextSibling, classtofind, topnode) > > elif (current.parentNode != topnode) \ > > and (current.parentNode.nextSibling != None): > > findelement(current.parentNode.nextSibling, classtofind, > topnode) > else: > > print 'Returning None...' > > return None > > # others (text, comment, etc) > > else: > > if current.nextSibling: > > findelement(current.nextSibling, classtofind, topnode) > > elif (current.parentNode != topnode) \ > > and (current.parentNode.nextSibling != None): > > findelement(current.parentNode.nextSibling, classtofind, > topnode) > else: > > print 'Returning None...' > > return None > > > > # parse the document > > blog = parse('/home/noah/dev/blog/template.html') > > > > # find a post > > postexample = findelement(blog.documentElement, 'post') > > > > print 'Got node: ', postexample > > - > > My output is this: > > - > html : > head : > title : > body : > h1 : > ul : > li : > h2 : > ol : > li : post > Returning node: > Got node:None > - > > The function finds the right element fine, and says it will return Element: li at -0x48599c74>, but the program gets None instead. What's > happening here? Any suggestions? You have a lot of cases where findelement is called recursively and then its return value is discarded instead of being turned into a return value to the caller. In those cases, execution simply falls off the end of the function and None is returned implicitly (and silently, since you don't have a print "Returning None" at the end of the function). HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Retain reference to a struct
On Wed, 2005-11-02 at 16:23, [EMAIL PROTECTED] wrote: > Hi All, > > A C library I'm using has a number of functions that all require a > struct as an argument. The example module shows how to make a new > Python Object from C code and I've seen other posts that recommend this > way of doing it. > > In this case though, it would seem easier if I could create the object > in the Python code. This would require storing a pointer to an > instance of the struct until a certain function is called. > > I can get the pointer into the python code, but whenever I try to use > it to call another function, the module segfaults. Can anyone suggest > why this is? > > static PyObject * > libpyq_PQconnectdb(PyObject *self, PyObject *args) > { > PGconn *conn = PyMem_New(PGconn, sizeof(PGconn *)); > conn = (PGconn *)PQconnectdb((const char*) > PyString_AS_STRING(args)); > > printf("%p", conn); > return PyLong_FromVoidPtr(conn) ; > } > > static PyObject * > libpyq_PQfinish(PyObject *self, PyObject *args) > { > printf("%p", args); > return 1; What exactly do you think you're returning here? The function declaration says that you're supposed to return a pointer to a PyObject. '1' is not likely to be a valid pointer to anything. > } > > >>> import libpyq#works fine > >>> conn = libpyq.PQconnectdb#conn now a pointer Are you sure that's the correct example code? As written, that line doesn't call the PQconnectdb function. It assigns "conn" to be an alternate name for the PQconnectdb function. > >>> libpyq.PQfinish(conn)#segfaults That's probably due to the fact that the python interpreter wants to look up your return value for printing it, but you're returning a bogus pointer. > I'm new to C but relatively experienced with Python. I have a sneaky > suspiscion there's a good reason for not doing it this way but I > haven't seen a good explanation of why not yet. If you know one, > please tell me. The idea of passing around pointers as numbers is very unpythonic. There is no guarantee that the number that's passed into PQfinish actually came from a call to PQconnectdb. The user could pass in any integer and (probably successfully) attempt to crash the system. You should really wrap the C struct (or the pointer to the C struct) into a Python object instead. By the way, it looks like you're trying to write some sort of database access module. The 'pq' looks suspiciously like it's for PostgreSQL. If that's the case, can't you just use an existing module for connecting to PostgreSQL? HTH, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python
On Sun, 06 Nov 2005 23:29:01 -, Jim Segrave wrote > In article <[EMAIL PROTECTED]>, > Little <[EMAIL PROTECTED]> wrote: > >cursor.execute( > >"""INSERT INTO InventoryList (artist, title, rating) VALUES (%s, > >%s, %s)""", (z_Name, z_rating, z_price) ) > > I hate to ask, but what happens when I enter "a, b, c);DROP > DATABASE;" as the entry for z_name? (Or some similar attempt to > close the SQL statement and start a new one). I think you want to > google for "SQL injection" and think about sanitising user input a bit. The OP is using execute() with a parameter tuple. This is the correct method for executing a parametrized query, and it is immune to SQL injection as long as the DB module implements parameter substitution in a sane way. Best regards, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
On Thu, 2005-11-10 at 16:53, Steven D'Aprano wrote: > Dude, a comprehension protection for *any* software can never be built > because of the fundamental nature of computers. Trying to stop bytes from > being copyable is like trying to stop water from being wet, and once > copied, all copies are identical and therefore indistinguishable. +1 QOTW! -- Carsten Haese - Software Engineer | Phone: (419) 794-2531 Unique Systems, Inc. | FAX: (419) 893-2840 1687 Woodlands Drive | Cell: (419) 343-7045 Maumee, OH 43537| Email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to avoid "f.close" (no parens) bug?
On Thu, 2 Nov 2006 23:56:22 +0200, o wrote > plez send me > Please tell us what bug you're talking about: A) Python closed the file but you expected it not to. B) Python didn't close the file but you expected it to. C) Python didn't warn you when you wrote "f.close" instead of "f.close()". D) Something else. Please elaborate by giving us a code example, a description of what you expected to happen, and a description of what happened instead. Best regards, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to - import code not in current directory
On Thu, 2005-11-17 at 08:41, py wrote: > Claudio Grondi wrote: > > so this should work in your case: > > > > import sys > > sys.path.append("C:\some\other\directory") > > import bar > > ...that will certainly work. Only issue is that each time I start up > foo.py in the python shell I have to retype those three lineskind > of why I was hoping for a environment variable or path setting that i > could stick in. That would be PYTHONPATH. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert a "long in a string" to a "long"?
On Fri, 2005-11-18 at 11:04, [EMAIL PROTECTED] wrote: > Hello, > > I need to convert the string "" to a long. To convert this > string I tried the following: > >>> 0x > -1 > >>> 0xL > 4294967295L > > OK, this is what I want, so I tried > > s = long("0xL") > ValueError: invalid literal for long(): 0xL > > s = long("0x") > ValueError: invalid literal for long(): 0xL > > What can I do? > > Thank you in advance. > Stefan Leave out the "0x" prefix and tell long() that you're using base 16: >>> long("", 16) 4294967295L HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Python API InformixDB-2.1 released
Hi everybody: I am proud to announce a new release of InformixDB, the IBM Informix implementation of the Python DB API. This release adds the following new features: * Scroll cursors and cursors with hold * Support for INTERVAL types * Support for Smart Large Objects * Support for User Defined Types Downloads and more info at http://informixdb.sourceforge.net/ Enjoy, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are there no ordered dictionaries?
On Tue, 2005-11-22 at 13:37, Christoph Zwerschke wrote: > Would the default semantics below really be that suprising? > > "An ordered dictionary remembers the order in which keys are first seen > [...] Overwriting an entry replaces > its value, but does not affect its position in the key order. Removing > an entry (using 'del') _does_ remove it from the key order. Accordingly, > if the entry is later recreated, it will then occur last in the key > order. [...]" > I can't help but I still find it unambiguous and intuitive enough to > consider it "the one" standard implementation for ordered dictionaries. I don't think it's intuitive if you can't describe it without contradicting yourself. If the order of the keys really were the order in which they were first seen by the dictionary, deleting and recreating a key should maintain its original position. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are there no ordered dictionaries?
On Tue, 2005-11-22 at 14:37, Christoph Zwerschke wrote: > In Foord/Larosa's odict, the keys are exposed as a public member which > also seems to be a bad idea ("If you alter the sequence list so that it > no longer reflects the contents of the dictionary, you have broken your > OrderedDict"). That could easily be fixed by making the sequence a "managed property" whose setter raises a ValueError if you try to set it to something that's not a permutation of what it was. > d1[0] + d1[2] ==> OrderedDict( (1, 11), (3, 13) ) What do you think you're doing here? -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are there no ordered dictionaries?
On Tue, 2005-11-22 at 20:44, Tom Anderson wrote: > On Tue, 22 Nov 2005, Carsten Haese wrote: > > > On Tue, 2005-11-22 at 14:37, Christoph Zwerschke wrote: > > > >> In Foord/Larosa's odict, the keys are exposed as a public member which > >> also seems to be a bad idea ("If you alter the sequence list so that it > >> no longer reflects the contents of the dictionary, you have broken your > >> OrderedDict"). > > > > That could easily be fixed by making the sequence a "managed property" > > whose setter raises a ValueError if you try to set it to something > > that's not a permutation of what it was. > > I'm not a managed property expert (although there's a lovely studio in > Bayswater you might be interested in), but how does this stop you doing: > > my_odict.sequence[0] = Shrubbery() It would only break if the getter returns the internal list directly. The getter should return a copy instead, which is what the keys() method already does anyway. This would ensure that the only way to alter the sequence is by replacing it in its entirety. -Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: syntax errors while building pypgsql
On Wed, 2005-11-23 at 08:01, Tin Gherdanarra wrote: > Hallo, > > I'm trying to install pypgsql. However, I get syntax errors > while compiling the C sources. The following excerpt > from pgconnection.h looks a little funny to me: > > typedef struct { > PyObject_HEAD /* Here is the syntax error, and rightly so */ > PGconn *conn; > PyObject *host; > PyObject *port; > PyObject *db; > PyObject *options; > PyObject *tty; > PyObject *user; > PyObject *pass; > PyObject *bePID; > PyObject *socket; > PyObject *version; > PyObject *notices; > PyObject *cinfo; > int showQuery; > } PgConnection; > > > I don't know what PyObject_HEAD or PGconn is, > but if they are types, a syntax error is justified here: PyObject_HEAD is not a type, it is a macro that defines struct members that all Python objects have in common. The macro definition has a semicolon at the end, so when the macro is expanded, the result is syntactically correct, even though the above looks wrong on the surface. What error messages are you actually getting? If you are getting a long list of errors, please give us the first few rather than the last few. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are there no ordered dictionaries?
On Wed, 2005-11-23 at 15:17, Christoph Zwerschke wrote: > Bengt Richter wrote: > > I think the concept has converged to a replace-or-append-by-key ordering > > of key:value items with methods approximately like a dict. We're now > > into usability aspects such as syntactic sugar vs essential primitives, > > and default behaviour vs selectable modes, ISTM. > > Yes, and we would be good if we do not stop the discussion at this point > with nothing, but really create such a sophisticated implementation. > Whether it will become popular or go to the standard lib some day is a > completely different question. > > > E.g., it might be nice to have a mode that assumes d[key] is > d.items()[k][1] when > > key is an integer, and otherwise uses dict lookup, for cases where > the use > > case is just string dict keys. > > I also thought about that and I think PHP has that feature, but it's > probably better to withstand the temptation to do that. It could lead to > an awful confusion if the keys are integers. Thus quoth the Zen of Python: "Explicit is better than implicit." "In the face of ambiguity, refuse the temptation to guess." With those in mind, since an odict behaves mostly like a dictionary, [] should always refer to keys. An odict implementation that wants to allow access by numeric index should provide explicitly named methods for that purpose. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are there no ordered dictionaries?
On Wed, 23 Nov 2005 23:39:22 +0100, Christoph Zwerschke wrote > Carsten Haese schrieb: > > > Thus quoth the Zen of Python: > > "Explicit is better than implicit." > > "In the face of ambiguity, refuse the temptation to guess." > > > > With those in mind, since an odict behaves mostly like a dictionary, [] > > should always refer to keys. An odict implementation that wants to allow > > access by numeric index should provide explicitly named methods for that > > purpose. > > Exactly. But I don't think in this case such methods would be > needed. You easily get the i-th value in the ordered dict as > d.values()[i]. > > -- Chris True enough, but unless the odict has its list of values on hand, you're asking the odict to build a list of all its values just so that you can get the i'th element. Having a method that does the equivalent of d[d.sequence[i]] would be cleaner and more efficient. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Cron to run a python program
On 23 Nov 2005 16:23:11 -0800, vagrantbrad wrote > I'm using python 2.4 running on Fedora Core 4. I have written a python > program called ipscan.py that checks the external ip address of my > cable internet connection, and on change, will update the dns records > at my dns provider, zoneedit. So basically, I've setup dynamic dns > using python. Once the ip compare and/or update is complete, I log the > results to a text file called update.log. When I run the program in > a bash shell with the command "python ipscan.py", the program runs fine > and the results are appended to update.log. When I run this program > as a cron job under the root user with the previously mentioned > command, the program runs without errors but does not append an > entry to the log. The permissions on the update.log file should not > be an issue since I'm running the cron job as root, but I've given > root write permissions just to be safe. What would cause the > logging to work at a command prompt but fail in cron? I'm not > getting any errors in the cron logs or /var/spool/mail/root. You're not giving us much detail about your script, so we can only guess. My guess is that your python script is either not invoked at all or it dies (raises an exception) before appending to the update.log. You should keep in mind that cron jobs don't run in a normal login shell, don't have the normal environment variables, and are not attached to a tty. Any of those factors can conceivably cause a script to fail under cron when it works fine from a shell. HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: python speed
On Wed, 2005-11-30 at 14:53, Paul Boddie wrote: > [...] the Java virtual machine > is suitably designed/specified to permit just-in-time complication. +1 Freudian slip of the week :) -Carsten Haese -- http://mail.python.org/mailman/listinfo/python-list
Re: Why use #!/usr/bin/env python rather than #!python?
On Fri, 2005-12-02 at 09:12, Adriano Ferreira wrote: > On 12/2/05, Klaus Alexander Seistrup <[EMAIL PROTECTED]> wrote: > > #v+ > > > > $ ls -l /tmp/hello.py > > -rwxr-xr-x 1 klaus klaus 38 2005-12-02 14:59 /tmp/hello.py > > $ cat /tmp/hello.py > > #! python > > print 'Hello, world!' > > # eof > > $ /tmp/hello.py > > bash: /tmp/hello.py: python: bad interpreter: No such file or directory > > $ > > > > #v- > > Hey, that's not fair. In your illustration above, does 'python' can be > found in the PATH? That is, > > $ python /tmp/hello.py > > works? If it does, probably > > #!/usr/bin/python > #!/usr/bin/env python > #!python > > would also work if > (1) 'python' is at '/usr/bin/python' (but that's inflexible) > (2) 'python' can be found in the environment variable path (if 'env' > is at '/usr/bin/env') > (3) 'python' can be found in the environment variable path (no need > for 'env' utility) (3) assumes that whatever shell the user is running looks up the shebang executable in the path, which bash, just to name one example, does not do. (2) and (1) require that you know where env and python live, respectively, that's true, but env is likely to be found in an OS-dependent standard location than python, so (2) is preferable. HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: insert a dictionary into sql data base
On Mon, 05 Dec 2005 18:00:21 -0700, David Bear wrote > Fredrik Lundh wrote: > > DON'T MANUALLY CONSTRUCT THE SQL INSERT STATEMENT. Use string > > formatting to insert the field names, but let the database layer deal with > > the values. > > > > If you want to do things in two steps, do the fields formatting first > > > > query = "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields)) > > > > and pass the query and the values sequence to the database layer: > > > > cursor.execute(query, values) > > > > The database will take care of the rest. > > > > > > I think I'm missing some important documentation somewhere. Here's > what I tried (using both % and $ signs): > > >>> sql > 'INSERT INTO nic (addr_code,ip_address,property_control,mac_address) > VALUES > (%s);' > > >>> sql2 > 'INSERT INTO nic (addr_code,ip_address,property_control,mac_address) > VALUES > ($s);' > >>> values > ['p', '129.219.120.134', '6154856', '00:40:50:60:03:02'] > > >>> cursor.execute(sql1, values) > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'sql1' is not defined > >>> cursor.execute(sql, values) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib64/python2.4/site-packages/pgdb.py", line 163, in execute > self.executemany(operation, (params,)) > File "/usr/lib64/python2.4/site-packages/pgdb.py", line 187, in > executemany > raise OperationalError, "internal error in '%s': %s" % (sql,err) > pg.OperationalError: internal error in 'INIT': not all arguments converted > during string formatting > > I get the same error if using $ sign. > > When I look at the pygresql dbapi official site at > http://www.pygresql.org/pgdb.html > > "this section needs to be written"... > > I would really appreciate some more examples on using pgdb (pygresql) It appears that Fredrik gave you good advice but bad example code. The example he gave you constructs an insert query with only one parameter placeholder. You'll need as many placeholders as the number of values that are inserted. The following example should work better: def insertDict(curs, tablename, data): fields = data.keys() values = data.values() placeholder = "%s" fieldlist = ",".join(fields) placeholderlist = ",".join([placeholder] * len(fields)) query = "insert into %s(%s) values (%s)" % (tablename, fieldlist, placeholderlist) curs.execute(query, values) The main thing to note here is that we *are* using string formatting to build a query that's based on a variable table name and a variable column list, but we *are not* using string formatting to fill in the values.[*] On a somewhat related note, it's unfortunate that many database modules use %s as parameter placeholders, because it makes it too tempting to write bad code such as cur.execute("insert into tab1(spam,eggs) values (%s,%s)" % (a,b)) # Bad, uses vulnerable and error-prone string formatting instead of cur.execute("insert into tab1(spam,eggs) values (%s,%s)", (a,b)) # Good, uses parameters. [*] This code blindly trusts that the table name and dictionary keys don't contain SQL injection attacks. If the source of these is not completely trustworthy, the code needs to be hardened against such attacks. I'll leave that as an exercise for the reader. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: i=2; lst=[i**=2 while i<1000]
On Tue, 2005-12-06 at 10:44, Steve Holden wrote: > Daniel Schüle wrote: > >>>i=2 > >>>lst=[] > >>>while i<1000: > >>>i**=2 > >>>lst.append(i) > >>> > >> > > > > unless I am missing something obvious, I can not see why the loop should > > not terminate > > In that case, kindly explain how the condition i<1000 can become false > when it starts at 2 and never changes! [In other words: you *are* > missing something obvious]. > > Don't you have an interpreter you could run the code in to verify that > it does indeed loop interminably? You seem to be assuming that the > expression i**2 changes the value of i. It doesn't. Note that the OP wrote i**=2, not i**2. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Spreadsheet with Python scripting and database interface?
On Fri, 2005-07-29 at 04:21, Wolfgang Keller wrote: > Hello, > > I'm looking for a spreadsheet application (MacOS X prefered, but > Windows, Linux ar available as well) with support for Python scripting > (third-party "plug-ins" are ok) and a database interface. > > Applications that I know of (that they exist) are: > > MS Excel > Quattro > Lotus > OO Calc > Gnumeric > Kspread > > Which ones have I forgotten? > > Which ones have support for Python scripting? > [snip] > OO Calc: I know that PyUNO exists, but I know nothing about what it can > actually do? > [snip] See http://udk.openoffice.org/python/python-bridge.html for more than you'll ever want to know about this. In a nutshell, you can do pretty much anything. One thing that's not clear from your question is whether you want to script the office from within using a macro or from the outside via "remote control". PyUNO allows both, but Python macros are only possible with the OpenOffice 2 scripting framework. Hope this helps, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Re: variable hell
On Thu, 2005-08-25 at 10:43, Nx wrote: > Thanks for the many replies > > here is an example for what it will be used for , in this case > fixed at 31 fieldvalues: > > > inputvalues=(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,s22,s23,s24,s25, > s26,s27,s28,s29,s30,s31) inputvalues = tuple(mylist) Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: variable hell
On Thu, 2005-08-25 at 11:04, I hastily wrote: > On Thu, 2005-08-25 at 10:43, Nx wrote: > > Thanks for the many replies > > > > here is an example for what it will be used for , in this case > > fixed at 31 fieldvalues: > > > > > > inputvalues=(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,s22,s23,s24,s25, > > s26,s27,s28,s29,s30,s31) > > inputvalues = tuple(mylist) And actually, you probably don't have to do that, because the execute method should be able to handle a list just as well as a tuple. -Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Find day of week from month and year
On Fri, 2005-09-02 at 16:46, Laguna wrote: > Paul, > > Thanks for the suggestion on calendar module. Here is my solution and > it works: > > def expiration(year, month): > weekday = calendar.weekday(year, month, 1) > table = [19, 18, 17, 16, 15, 21, 20] > return table[weekday] > > Cheers, > Laguna This, of course, can be "optimized" into def expiration(year, month): return [19,18,17,16,15,21,20][calendar.weekday(year,month,1)] ;) -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb error - PLEASE SAVE ME!
On Sat, 17 Sep 2005 15:50:29 -0400, Ed Hotchkiss wrote > Ok. I am trying to read a csv file with three strings separated by commas. > I am trying to insert them into a MySQL DB online. > MySQLdb is installed, no problems. > > I think that I am having some kind of error with my csv going into > the fields and being broken apart correctly. Can someone please > help? I attached the code below, it does work with that SQL server > also if you want to try and run it. Thanks in advance .. There are two obvious faults in your code: 1) You're using the % operator to plug your parameters directly into the query string. Don't do that. Pass the parametrized query as the first argument to execute(), pass the parameter tuple as the second argument to execute(), and leave it to execute() to plug in the parameters. Once 1) is fixed, you'll run into... 2) The ID column is a NOT NULL column. There is no default value for it, nor is there an AUTO_INCREMENT flag on it. You're not specifying a value for ID in the insert statement. Either this will fail on the first insert (attempting to insert a NULL value into a NOT NULL column), or in case MySQL helpfully defaults the ID to 0, it'll fail on the second row when the primary key constraint is violated by attempting to insert another 0. To fix 2), you'll wither want to make the ID column an AUTO_INCREMENT column or explicitly specify a value for the ID column in the insert statement. (Using AUTO_INCREMENT is easier.) Hope this helps, Carsten. P.S. You need to learn how to describe your problem accurately. Phrases like "no problems" and "it does work" juxtaposed with "some kind of error" do nothing to describe what actually works and what doesn't work. I'm betting python raised an exception when you ran your code. Instead of guessing randomly (and incorrectly) that there is some kind of error in your csv parsing, you could have, for example, included a copy of the exception message. -- http://mail.python.org/mailman/listinfo/python-list
InformixDB-1.5 released
Hi Everybody: I have released a new version, version 1.5, of InformixDB, the DB-API module for connecting to IBM Informix database engines. Download at http://sourceforge.net/projects/informixdb . Notable changes since version 1.4: * Further steps towards DB-API 2 compliance: added recommended keyword arguments to connect() method and implemented cursor methods/attributes .next(), .executemany(), .rowcount, and .arraysize * informixdb.Error now makes details about the error (such as sqlcode) available as attributes. * sqlerrd wasn't initialized properly, and under many circumstances it didn't correspond to the most recent operation. Best regards, Carsten Haese. -- http://mail.python.org/mailman/listinfo/python-list
Looking for Stephen Turner, maintainer of informixdb
Hello everybody: I have discovered that the functionality for connecting Python to an Informix database is currently in a frustrating state of neglect. The link to Kinfxdb is dead, and informixdb doesn't build on Python 2. I couldn't find any usable workarounds to the build problem, so I worked out successfully how to build informixdb using distutils. Now I'd like to share the result with the community, but the maintainer appears to have gone missing. My emails to [EMAIL PROTECTED] and [EMAIL PROTECTED] have bounced back undeliverable, so now I'm posting to the lists trying to locate Stephen. If anybody has any pointers for locating Stephen Turner, please let me know. If Stephen can't be located, I'd be willing to take over the project, but I'd prefer the torch be given to me rather than me just taking it. Thanks, -- Carsten Haese - Software Engineer |Phone: (419) 861-3331 Unique Systems, Inc. | FAX: (419) 861-3340 1446 Reynolds Rd, Suite 313 | Maumee, OH 43537| mailto:[EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for Stephen Turner, maintainer of informixdb
On Tue, 2005-03-29 at 03:05, Michael Husmann wrote: > Carsten Haese wrote: > > > Hello everybody: > > > > I have discovered that the functionality for connecting Python to an > > Informix database is currently in a frustrating state of neglect. The > > link to Kinfxdb is dead, and informixdb doesn't build on Python 2. I > > couldn't find any usable workarounds to the build problem, so I worked > > out successfully how to build informixdb using distutils. > > > > Now I'd like to share the result with the community, but the maintainer > > appears to have gone missing. My emails to [EMAIL PROTECTED] and > > [EMAIL PROTECTED] have bounced back undeliverable, so now I'm > > posting to the lists trying to locate Stephen. > > > > If anybody has any pointers for locating Stephen Turner, please let me > > know. If Stephen can't be located, I'd be willing to take over the > > project, but I'd prefer the torch be given to me rather than me just > > taking it. > > Carsten, > > haven't heard anything from Stephen either, but there are some extensions to > the informixdb module. I'll send the sources to you next week. So if you > like you can bundle everything in one package. Michael, I'd certainly like to take a look at those extensions. (I tried to respond to you off-list, but my mail bounced back. Is this project cursed or am I? :) I hope you're reading this, Michael.) A week has gone by with no replies as to Stephen's whereabouts, and one reply telling me that I can, in good faith, go ahead and release a fork. Unless somebody tells me I should wait longer, I guess I'll do that. Stay tuned for the announcement on when and where my fork will be available. Best regards, -- Carsten Haese - Software Engineer |Phone: (419) 861-3331 Unique Systems, Inc. | FAX: (419) 861-3340 1446 Reynolds Rd, Suite 313 | Maumee, OH 43537| mailto:[EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Ply(LALR) and Yacc behaving differently
On Thu, 2005-04-07 at 14:51, Åsmund Grammeltvedt wrote: > Hi. > > I am trying to implement a small compiler in python and, trying to use > something a bit more pythonic than lex/yacc, ended up with ply > (http://systems.cs.uchicago.edu/ply/). The only problem is that whereas > yacc accepts the grammar and appears to parse it correctly, ply does not. > > Perhaps this belongs on some compiler list, but I couldn't decide if it > was a compiler or a python problem, so bear with me. Maybe this is a PLY bug? LALR(1) support appears to be a relatively recent addition to PLY. Have you tried contacting PLY's author? For what it's worth, it appears that you can make your example grammar work in LALR-mode PLY by eliminating the empty production and making the Block rule right recursive like this: def p_Goal(p): """ Goal : Block """ def p_Block(p): """ Block : SEMI | T Block | S Block """ Of course, I don't know whether this rewrite is applicable to your larger grammar. Hope this helps, -- Carsten Haese - Software Engineer |Phone: (419) 861-3331 Unique Systems, Inc. | FAX: (419) 861-3340 1446 Reynolds Rd, Suite 313 | Maumee, OH 43537| mailto:[EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Informixdb: New maintainer, new version
Hi Everybody: Since the current maintainer of the informixdb module appears to have gone missing, I have decided to take over the project. The new home of the informixdb module is http://sourceforge.net/projects/informixdb . Version 1.4 features the following improvements: * Build uses distutils instead of deprecated Makefile.pre.in mechanism. * Connect method takes optional username and password parameters for connecting to a remote database. * Cursor attribute .sqlerrd exposes Informix's sqlca.sqlerrd resulting from the cursor's most recent .execute() call. If you have any questions or comments, please let me know. Best regards, -- Carsten Haese - Software Engineer |Phone: (419) 861-3331 Unique Systems, Inc. | FAX: (419) 861-3340 1446 Reynolds Rd, Suite 313 | Maumee, OH 43537| mailto:[EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: "0 in [True,False]" returns True
On Mon, 2005-12-12 at 16:26, Pierre Quentel wrote: > Hi all, > > In some program I was testing if a variable was a boolean, with this > test : if v in [True,False] > > My script didn't work in some cases and I eventually found that for v = > 0 the test returned True > > So I changed my test for the obvious "if type(v) is bool", but I still > find it confusing that "0 in [True,False]" returns True > > By the way, I searched in the documentation what "obj in list" meant and > couldn't find a precise definition (does it test for equality or > identity with one of the values in list ? equality, it seems) ; did I > miss something ? Where/how did you search? http://docs.python.org/lib/typesseq.html states unambiguously that "x in s" returns "True if an item of s is equal to x, else False" HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python C/API - *arg,**kwds variable argumnents
On Wed, 2005-12-14 at 12:00, [EMAIL PROTECTED] wrote: > essentially I already use PyArg_ParseTupleAndKeywords, but that seems > to emulate fixed arg list definitions like - >func (x,y,t=0,u=1) It's unclear what you are actually trying to accomplish. My guess is that you want to implement a function/method that takes any number of arbitrarily named keyword arguments. If that is the case, you can simply use the dictionary that is passed to your C function as the third argument. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Easiest way to calculate number of character in string
On Wed, 2005-12-21 at 09:03, P. Schmidt-Volkmar wrote: > Hi there, > > I have a string in which I want to calculate how often the character ';' > occurs. If the character does not occur 42 times, the ";" should be added so > the 42 are reached. > > My solution is slow and wrong: > for Position in range (0, len(Zeile)): > if Zeile[Position]==';': AnzahlSemikolon = AnzahlSemikolon +1 > if AnzahlSemikolon < 42: > for Zaehler in range(AnzahlSemikolon, 42): > Zeile = Zeile + ';' > Dreckskram = Dreckskram +1 > > How can this be achieved easily? > > Thanks, > > Pascal AnzahlSemikolon = Zeile.count(';') if AnzahlSemikolon < 42: Zeile += ';'*(42-AnzahlSemikolon) HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
On Thu, 2005-12-22 at 07:01, Peter Hansen wrote: > [EMAIL PROTECTED] wrote: > > So exactly how high is python in Google's priority list ? Or in other > > words, if python is in a stand still as it is now, what would be the > > impact to Google ? > > Since when is Python in a standstill? I believe bonono meant the question in the hypothetical sense of "If Python would stand still in its current state, what would be the impact to Google?" but didn't know how to ask it correctly. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
On Thu, 2005-12-22 at 08:18, [EMAIL PROTECTED] wrote: > Cameron Laird wrote: > > In article <[EMAIL PROTECTED]>, > > <[EMAIL PROTECTED]> wrote: > > . > > . > > . > > >Well, this may be the CPython way of open source but I don't know if > > >that is "Open source" in general. Another way is that if someone(or > > >group) don't like the current state of a project, they fork. I don't > > >know if that is possible in the context of python, and programming > > >language in general. Can it still be called python ? > > . > > . > > . > > While I don't understand the question, it might be pertinent to > > observe that, among open-source development projects, Python is > > unusual for the *large* number of "forks" or alternative imple- > > mentations it has supported through the years > http://phaseit.net/claird/comp.lang.python/python_varieties.html >. > The question is, can anyone just fork a new one using the python name, > as part of the project, without the permission from the foundation ? > Say for example, anyone want to implement java needs permission from > Sun(or is it javasoft), if I rememeber correctly. Therefore, the only > way to make change to java the language is to convince Sun, very > similar to the model of Python. But many open source project is not > using this model. Most of your question can be answered by reading the license. Section 3 of version 2 of the PSF license states: """ 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. """ In other words, you can change Python to your liking and distribute the changed version, as long as you tell people how it differs from Python. Since the changed version is different from Python, calling it Python would be a) boneheaded and b) as Steve Holden points out, a trademark violation. Note that section 7 states that "This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party" and the Python name is a trademark of the PSF. So, if there is something you don't like about Python, you have two choices: 1) Seek consensus with the Python community and have your changes accepted into the "official" Python version, or 2) Fork Python into something else with a different name. If the different name contains 'Python', you'll probably have to ask PSF for permission. In any case, as outlined above, you have have to state that the fork is based on Python and summarize how it differs from Python. Hope this clears things up, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: print UTF-8 file with BOM
> 2005/12/23, David Xiao <[EMAIL PROTECTED]>: > Hi Kuan: > > Thanks a lot! One more question here: How to write if I want > to > specify locale other than current locale? > > For example, running on Korea locale system, and try read a > UTF-8 file > that save chinese. Use the encode method to translate the unicode object into whatever encoding you want. unicodeStr = ... print unicodeStr.encode('big5') Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying values in a list
On Thu, 2005-12-29 at 11:43, [EMAIL PROTECTED] wrote: > The following code: > > numbers = [1, 2, 3] > for value in numbers: > value *= 2 > print numbers > > results in the following output: > [1, 2, 3] > > The intent of the code was to produce this output: > [2, 4, 6] > > What is the reason for the output produced? > What code should be used to obtain the desired output? 1) Read http://www.effbot.org/zone/python-objects.htm and reread it until you understand why your code doesn't work. 2) Use a list comprehension: numbers = [ value*2 for value in numbers ] -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: MidiToText : EventDispatcher instance has no attribute 'sysex_events'
On Fri, 2005-12-30 at 09:52, tim wrote: > Trying to convert midi to text using MidiToText.py. > I get the following: > > midi_port: 0 > Traceback (most recent call last): > File "MidiToText.py", line 176, in ? > midiIn.read() > File "C:\Python24\Lib\site-packages\midi\MidiInFile.py", line 24, in read > p.parseMTrkChunks() > File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 167, > in parseMTrkChunks > self.parseMTrkChunk() # this is where it's at! > File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 129, > in parseMTrkChunk > dispatch.sysex_events(sysex_data) > AttributeError: EventDispatcher instance has no attribute 'sysex_events' Try changing "def sysex_event(self, data):" in ...\midi\EventDispatcher.py to "def sysex_events(self, data):" Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and location of .so files?
On Tue, 2006-01-10 at 09:42, Efrat Regev wrote: >Hello, > >On FC4, I've generated an .so file from C++ which I want to use from > python. It works when I copy it into /usr/lib/python2.4/site-packages. > (I.e., say I have hello.so in that directory, then from the python > prompt I can 'import hello', and the code works fine). The problem is > that the said directory requires su - so I'd rather python load my .so > from a different user-privilege directory (when I type 'import hello'). > Is there some way to tell python to use a different directory? Yes. See http://docs.python.org/tut/node8.html#SECTION00811 for information on Python's module search path. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: rational numbers
On Tue, 2006-01-17 at 11:22, Paul Rubin wrote: > Schüle Daniel <[EMAIL PROTECTED]> writes: > > does anybody know modules which make rational numbers available? > > Try gmpy.mpq (google for gmpy). > > > and are there considerations to add them to the core, like > > complex numbers (maybe in Python 3) > > I don't think it's been discussed much. Somebody must have discussed it. There is a rejected PEP for adding a Rational type to python: http://www.python.org/peps/pep-0239.html -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Help with Python/C API
On Thu, 2006-01-19 at 00:44, pycraze wrote: > Hi guys, > > I Need to know how do i create a dictionary... eg: > n = pali_hash > n={} > n={1:{ } } -> i need to know how to make a key of a dictionary, to a > dictionary using Python/C API's You can either use Py_BuildValue (See http://docs.python.org/api/arg-parsing.html#l2h-214) or PyDict_New and PyDict_SetItem (See http://docs.python.org/api/dictObjects.html) to construct a dictionary. Good luck, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Static Variables in Python?
On Mon, 2006-07-31 at 15:21, Michael Yanowitz wrote: > Is it possible to have a static variable in Python - > a local variable in a function that retains its value. > > For example, suppose I have: > > def set_bit (bit_index, bit_value): >static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >bits [bit_index] = bit_value > >print "\tBit Array:" >int i >while (i < len(bits): > print bits[i], >print '\n' > > >I realize this can be implemented by making bits global, but can > this be done by making it private only internal to set_bit()? I don't > want bits to be reinitialized each time. It must retain the set values > for the next time it is called. Python does not have static variables in the sense that C does. You can fake it in various ways, though. If I had to do it, I'd define a callable object instead of a function, along the lines of this: class BitSetter(object): def __init__(self): self.bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] def __call__(self, bit_index, bit_value): self.bits[bit_index] = bit_value # do something with self.bits here... print self.bits set_bit = BitSetter() Now you can call set_bit(...) as if it were a function, and it'll behave the way you want. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get LCHARVAR's with InformixDB
On Tue, 2006-08-01 at 09:02, [EMAIL PROTECTED] wrote: > I'm using the InformixDB package, which has been a real lifesaver, but > I'm finding I can't get any data from the Informix LCHARVAR types. > They're coming in as empty strings. > > The cursor._description for the field in question is: > ('msg_text', 'lvarchar', 0, 0, None, None, 1) > > Appreciate any help... thanks. What version are you using? I thought I fixed lvarchars a long time ago. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get LCHARVAR's with InformixDB
On Tue, 2006-08-01 at 09:27, [EMAIL PROTECTED] wrote: > Carsten Haese wrote: > > What version are you using? I thought I fixed lvarchars a long time ago. > > 2.2, with Python 2.4 on Windows... I installed via > InformixDB-2.2.win32-py2.4.exe Hm, this certainly warrants further investigation. I don't use lvarchars myself, so it's possible that I did something that accidentally broke the output binding for lvarchars. Could you possibly send me a minimal test script that shows the problem? Also, in case it matters, I'd like to know which versions of IDS and CSDK or Informix Connect you're using. Thanks, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get LCHARVAR's with InformixDB
On Tue, 2006-08-01 at 11:41, [EMAIL PROTECTED] wrote: > Carsten Haese wrote: > > Could you possibly send me a minimal test script that shows the problem? > > Also, in case it matters, I'd like to know which versions of IDS and > > CSDK or Informix Connect you're using. > > > Here's a sample script: > > sql = '''select msg_tx from dev_log''' > import informixdb > conn = informixdb.connect('mydb') > cursor = conn.cursor() > cursor.execute(sql) > print 'description is <%s>' % cursor.description > print cursor.fetchall() Thanks, but I can't use this to reproduce the problem. I'll need the create table statement for dev_log. > Output is: > description is <('msg_tx', 'lvarchar', 0, 0, None, None, 1)> > [('',), ('',), ('',), ('',), ('',), ('',)] > > But one of them should be: > '''Something:SomethingElse - going for 221 possibilities [User: > HOST-NAME\XYZZY]: > IdOtherData > 5878 C > 5968 X > 6732 V > [many more lines like this] > ''' > > Some hunting around, and I found this: > > C:\Program Files\Informix\Client-SDK\bin>esql > IBM Informix CSDK Version 2.80, IBM Informix-ESQL Version 9.52.TC1 > > Not sure what IDS is... the Informix Server version is: 9.3 FC3, > according to the DBA guy. IDS = Informix Dynamic Server. The version numbers you gave me are what I was looking for. For what it's worth, I've tried a simple test script on my Linux server that creates a temp table with an lvarchar column, inserts into it, and reads from it, all without a problem. However, there are many differences between my test environment and yours, and I'll need to know your specific circumstances to isolate which difference is causing the problem. Thanks, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get LCHARVAR's with InformixDB
On Tue, 2006-08-01 at 11:47, [EMAIL PROTECTED] wrote: > Another thing... > > > Output is: > > description is <('msg_tx', 'lvarchar', 0, 0, None, None, 1)> > > The 0's worried me, as I could see where they could be used as parms to > allocate/trim things as necessary... just a thought. That is indeed a problem. For some as of yet undetermined reason, the client thinks that msg_tx is a column of length zero, so it's no big surprise that all you get back is empty strings. Once again, I'll need the create table statement for the table you're selecting from in order to investigate what's happening. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get LCHARVAR's with InformixDB
On Tue, 2006-08-01 at 14:05, [EMAIL PROTECTED] wrote: > Carsten Haese wrote: > > Once again, I'll need > > the create table statement for the table you're selecting from in order > > to investigate what's happening. > > Here it is: > > CREATE TABLE DEV_LOG( > LOG_ID SERIAL, > LEVEL VARCHAR (10), > POI_NM VARCHAR (255), > MSG_TX LVARCHAR(2000), > MSG2_TX LVARCHAR(5000) > ) LOCK MODE ROW; The following test script works fine for me: - import informixdb conn = informixdb.connect("mydb") cur = conn.cursor() cur.execute(""" CREATE temp TABLE DEV_LOG( LOG_ID SERIAL, LEVEL VARCHAR (10), POI_NM VARCHAR (255), MSG_TX LVARCHAR(2000), MSG2_TX LVARCHAR(5000))""") str1 = "ABCDEFGHIJ"*200 str2 = "ABCDEFGHIJ"*500 cur.execute("insert into dev_log values(?,?,?,?,?)", (0,'MEDIUM','TESTMAN',str1,str2) ) cur.execute("select * from dev_log") row = cur.fetchone() assert row[3]==str1 assert row[4]==str2 print cur.description - I have tested this two ways, once directly on the server on Linux, once with a client-server connection from Windows to Linux. In both cases, both lvarchars are being read back correctly. One notable difference between your environment and mine is that I'm using CSDK version 2.90.TC3, which is more recent than the version of CSDK that you're using. I'd suggest upgrading to the newest version of CSDK. Please let me know what happens after the upgrade. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Negative division bug?
On Thu, 2006-08-03 at 13:51, Michael Yanowitz wrote: > Hello: > > Just wondering if this is a bug, is this as designed, > or do I have to import math or something to make it correct: > >I was just screwing around. > and found: > >>> -1/100 > -1 > Shouldn't it be zero? > 1/100 returns 0 > but -1/ANY_POSITIVE_INTEGER_NUMBER > returns -1 > > >>> -10/3 > -4 > >It behaves correct for positive numbers, but for negative > integers it seems to subtract one from the expected result. It behaves correctly in both cases. Your expectation is incorrect. http://docs.python.org/ref/binary.html says: """ Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the `floor' function applied to the result. """ The floor of x is the largest integer number that's less than or equal to x. The floor of -0.01 is -1. HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
On Tue, 2006-08-22 at 12:34, jojoba wrote: > Hello again, > > Fredrick said: > > > Python's object model. an object has a value, a type, and an identity, > > but no name. > > I say: > > Thank you Fredrick for the reply! > However, although python's object model does not currently support what > i am asking for, how difficult would it be to assign a string name(s) > to an object upon creation (and upon referencing)? > > please note: > i don't want to do anything sophisticated with this, i am really only > looking for a TITLE for my dictionary when i throw it in a tree editor > that i have built. And i do realize that its not possible now. I am > just pressing a point here. At the risk of stating the obvious, why don't you simply add a parameter for the title in the invocation of the tree editor? I.e. instead of invoke_tree_editor(somedict) do invoke_tree_editor(somedict, "somedict") HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I put % in a format sting?
On Thu, 2006-10-05 at 16:15, John Salerno wrote: > But I think SQL has other recommended methods. At least with SQLite, it > is recommended you not use Python's %s formatter but instead the "?" > formatter. While I wholeheartedly agree with the sentiment, calling the "?" a formatter only blurs the already blurred distinction between string formatting and parameter passing. The "?" is a parameter placeholder. I'm not gonna go into the reasons for why one should always use parametrized queries instead of rolling queries via string formatting, but the keywords are "SQL injection attack" and "poor performance". I would like to point out, though, that parameter passing in DB-API compliant database access modules is in general very different from string formatting. In most databases, when you say cur.execute("update sometable set somecolumn = ? where somekey = ?", ("spam", "eggs")), the database driver does *not* build a query string with string literals for "spam" and "eggs" substituted into the query. Real databases have a native API that allows passing a parametrized query and a set of parameter bindings, no string substitution required or desired. Some databases do not have such an API, and their respective DB-API modules emulate parameter passing by string substitution, but that is an implementation detail nobody should care about. However, it is precisely those databases that blur the distinction between parameter passing and string substitution, especially because their implementations tend to use "%s" parameter placeholders to make the internal string substitution easier, thus leaking an implementation detail into application code in an unfortunate way. (This is also the reason why I'd like to see %s parameter placeholders banned from future versions of the DB-API spec.) The bottom-line is, when writing parametrized queries, the "?" or "%s" or whatever is used to indicate that "here be parameters" is a parameter placeholder, not a formatter. Thanks for listening, I hope somebody out there finds this helpful ;) -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with the 'math' module in 2.5?
On 14 Oct 2006 20:33:13 -0700, Chris wrote > >>> from math import * > >>> sin(0) > 0.0 > >>> sin(pi) > 1.2246063538223773e-016 > >>> sin(2*pi) > -2.4492127076447545e-016 > >>> cos(0) > 1.0 > >>> cos(pi) > -1.0 > >>> cos(2*pi) > 1.0 > > The cosine function works fine, but I'm getting weird answers for sine. > Is this a bug? Am I doing something wrong? You're apparently not correctly reading python's answer to sin(pi). 1.2246063538223773e-016 is the scientific notation for the number 0.00012246063538223773, which is pretty darn close to zero, the result you probably expected. You're not getting *exactly* zero because you're not passing in *exactly* pi but a close approximation of pi. I'll leave it as an exercise for the reader to explain why cosine seems to work fine. Hint: Look at cos(pi/2) and sin(pi/2). -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange Behavior
On Mon, 2006-10-16 at 10:51, Steven D'Aprano wrote: > On Mon, 16 Oct 2006 07:26:05 -0700, abcd wrote: > > > class Foo: > > def __init__(self, name, data=[]): > > The binding of the name "data" to the empty list happens at compile time, > not runtime. I think this statement needs to be clarified. The binding of "data" to the empty list *does* happen at runtime, not at compile time. However, the binding happens only once, when the "def" statement is executed, as opposed to every time the __init__ function is called. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: datetime conversion question
On Tue, 2006-10-17 at 08:43, kevin evans wrote: > Hi, > I'm trying to convert some code from Ruby to Python, specifically.. > > timestamp = "%08x" % Time.now.to_i > > Make a hex version of the current timestamp. Any ideas how best to do > this in python gratefully received.. import time timestamp = "%08x" % int(time.time()) -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: datetime conversion question
On Tue, 2006-10-17 at 08:49, hg wrote: > import time > "%08X"% (int)(time.mktime(time.localtime())) Have you not had your coffee yet or are you trying to win an obfuscated python programming competition? ;) -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Tertiary Operation
On Tue, 2006-10-17 at 09:30, abcd wrote: > x = None > result = (x is None and "" or str(x)) > > print result, type(result) > > --- > OUTPUT > --- > None The "condition and result1 or result2" trick only works if result1 is an expression with a True boolean value. The empty string has a false boolean value. You could force result1 to have a true boolean value by sticking it into a list thusly: result = (x is None and [""] or [str(x)])[0] But that's ugly. Use Python 2.5 where there is a true conditional expression or find another way to solve your problem. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Tertiary Operation
On Tue, 2006-10-17 at 09:48, Tim Chase wrote: > [...] > Either of the following should suffice: > > # return a non-empty string > x is None and "None" or str(x) This one can be "optimized" to just str(x) since str(None)=="None". >[...] > There are more baroque ways of writing the terniary operator in > python (although I understand 2.5 or maybe python 3k should have > a true way of doing this). Python 2.5 does already. > My understanding is that one common > solution is something like > > {True: "", False: str(x)}[x is None] As Fredrik pointed out in not so many words, this is not a good solution. Besides being ugly, the major problem with this solution is that both branches are evaluated regardless of the outcome of the condition. This is not good if the expression is unsafe to calculate under the wrong condition, or if the expressions are expensive to calculate, or if the expressions have side effects. The "condition and result1 or result2" hack at least prevents the evaluation of the non-applicable expression due to the short-circuiting nature of the "and" and "or" operators. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: proper format for this database table
On Fri, 2006-10-20 at 10:57, John Salerno wrote: > [EMAIL PROTECTED] wrote: > > > you should rethink it as > > > > [id] [university] [yearStart] [yearEnd] [degreeEarned] > > 1 U of I 19711975 BS > > 1 U of I 19751976 MS > > 1 U of I 19761977 PhD > > > > Thanks guys. I do plan to have an id entry for each person as well, I > just forgot to mention that. But since it's a primary key, I didn't know > I could list it more than once. Or does primary key not necessarily mean > unique? Primary key *does* mean unique in the table that defines it. However, if you take a primary key ID from one table and store it in a different table, that's a foreign key. There are no inherent uniqueness constraints on a foreign key. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension (searching for onliners)
On Fri, 2006-10-20 at 10:53, Fredrik Lundh wrote: > if you want to become a good Python programmer, you really need to get > over that "I need a oneliner" idea. +1 QOTW -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: why does this unpacking work
On Fri, 2006-10-20 at 15:14, John Salerno wrote: > I'm a little confused, but I'm sure this is something trivial. I'm > confused about why this works: > > >>> t = (('hello', 'goodbye'), > ('more', 'less'), > ('something', 'nothing'), > ('good', 'bad')) > >>> t > (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), > ('good', 'bad')) > >>> for x in t: > print x > > > ('hello', 'goodbye') > ('more', 'less') > ('something', 'nothing') > ('good', 'bad') > >>> for x,y in t: > print x,y > > > hello goodbye > more less > something nothing > good bad > >>> > > I understand that t returns a single tuple that contains other tuples. t doesn't "return" anything, t *is* a nested tuple. > Then 'for x in t' returns the nested tuples themselves. It again doesn't "return" anything. It assigns each element of tuple t to x, one by one, executing the loop body for each element. > But what I don't understand is why you can use 'for x,y in t' when t > really only returns one thing. I see that this works, but I can't quite > conceptualize how. I thought 'for x,y in t' would only work if t > returned a two-tuple, which it doesn't. You're thinking of "x,y = t". > What seems to be happening is that 'for x,y in t' is acting like: > > for x in t: > for y,z in x: > #then it does it correctly No, it's actually behaving like for x in t: y,z = t # do something with y and z You seem to have difficulty distinguishing the concept of looping over a tuple from the concept of unpacking a tuple. This difficulty is compounded by the fact that, in your example above, you are looping over a tuple of tuples and unpacking each inner tuple on the fly. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: why does this unpacking work
On Fri, 2006-10-20 at 15:37, Carsten Haese wrote: > for x in t: > y,z = t > # do something with y and z Typo here, of course I mean y,z = x. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting by item_in_another_list
On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote: > At Tuesday 24/10/2006 04:35, Cameron Walsh wrote: > > > > c = set(B) > > > a.sort(key=c.__contains__, reverse=True) > > > > > > Tim Delaney > > > >Depressingly simple. I like it. > > ...and fast! ...and not guaranteed to be correct: http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states: """ Whether the sort() method is stable is not defined by the language (a sort is stable if it guarantees not to change the relative order of elements that compare equal). In the C implementation of Python, sorts were stable only by accident through Python 2.2. The C implementation of Python 2.3 introduced a stable sort() method, but code that intends to be portable across implementations and versions must not rely on stability. """ -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting by item_in_another_list
On Tue, 2006-10-24 at 11:41, Carsten Haese wrote: > On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote: > > At Tuesday 24/10/2006 04:35, Cameron Walsh wrote: > > > > > > c = set(B) > > > > a.sort(key=c.__contains__, reverse=True) > > > > > > > > Tim Delaney > > > > > >Depressingly simple. I like it. > > > > ...and fast! > > ...and not guaranteed to be correct: > > http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states: > > """ > Whether the sort() method is stable is not defined by the language (a > sort is stable if it guarantees not to change the relative order of > elements that compare equal). In the C implementation of Python, sorts > were stable only by accident through Python 2.2. The C implementation of > Python 2.3 introduced a stable sort() method, but code that intends to > be portable across implementations and versions must not rely on > stability. > """ > > -Carsten And I noticed a bit to late that the search on python.org lead me to an outdated version of the docs. The current documentation states that "Starting with Python 2.3, the sort() method is guaranteed to be stable." However, it's not clear whether this specifies language behavior that all implementations must adhere to, or whether it simply documents an implementation detail of CPython. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: what's the difference between these two methods? (aka, why doesn't one of them work?)
On Thu, 2006-11-02 at 12:28 -0800, JohnJSal wrote: > Can someone explain to me why the first version of this method works, > but the second one doesn't? All I've changed (I think) is how the > information is nested. The error I'm getting is that the call to > xrc.XRCCTRL is not working in the second example. Instead of getting > the appropriate widget, it's returning None. Is this a result of the > nesting, or the for loops perhaps? > [...] > Traceback (most recent call last): > File "C:\Python25\myscripts\labdb\dbapp.py", line 91, in OnSaveRecord > table_values.append(xrc.XRCCTRL(tab, textfield_id).GetValue()) > AttributeError: 'NoneType' object has no attribute 'GetValue' > You might find it helpful to inspect (e.g. print) textfield_id before the line that causes the exception. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: what's the difference between these two methods? (aka, why doesn't one of them work?)
On Thu, 2006-11-02 at 13:14 -0800, JohnJSal wrote: > JohnJSal wrote: > > JohnJSal wrote: > > > Peter Otten wrote: > > > > > > > > > > ...the above is not a 1-tuple, but an ordinary string. You forgot the > > > > trailing comma: > > > > > > > > ('notes',) > > > > > > Right you are! Now it works! :) > > > > > > Thanks! > > > > Oh great, now I've moved on to another issue. It seems that the list > > appending isn't working right. All that gets added to a list is the > > last value, not everything. Am I doing something wrong with the append > > method? > > Ah, got it! I was reinitializing the table_values list in the wrong > place The fact that you were able to answer your own question only a few minutes later indicates to me that you should set your "I give up and ask the list" threshold a tad higher. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators
On Wed, 2006-11-08 at 12:37 -0800, John Henry wrote: > I must be very thick. I keep reading about what decorators are and I > still don't have a good feel about it. See, for example: > > http://alex.dojotoolkit.org/?p=564 > > and: > > http://soiland.no/software/decorator > > What exactly do I use decorators for? Decorators are a tool for executing common code when a function is defined and/or when it's called. This reduces code duplication by allowing you to factor out commonly performed steps. If you find yourself writing different functions that share a lot of setup/teardown code, or if you find yourself doing a lot of repetitive housekeeping for each function you're defining, decorators eliminate this duplication. You've already been given a bunch of different examples, so I won't bore you with more contrived examples. If none of the examples make you say "wow, I could use this" and if you don't find yourself writing repetitive setup/teardown/housekeeping code, you can probably live quite comfortably without using decorators. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Fredrik Lundh [was "Re: explicit self revisited"]
On Sat, 2006-11-11 at 23:14 -0800, Doug wrote: > Fredrik Lundh wrote: > > Doug wrote: > >> > >> Fredrik Lundh wrote: > >>> Fredrik Lundh wrote: > >>> > cannot all you clueless trolls who cannot think of a single useful thing > >>> > to contribute to Python start your own newsgroup? > >> > >>> and before anyone complains; please note that they're working through > >> > >>> http://www.effbot.org/pyfaq/design-index.htm > >> > >> That site is a bunch of FUD - > >> The explicit self is there simply because OOP was tacked onto python as > >> an afterthought. > >> Why not just be honest about it. It's too late to change Python's > >> syntax. It just means a little extra typing. If it really bothers > >> someone, use "s" instead of "self" or else use Ruby. > > > > the official FAQ is a bunch of FUD? are you sure you know what FUD means? > > > > > > You idiot. Putting the word "official" in front of something doesn't > mean it can't be FUD. Fredrik doesn't have to prove that the official FAQ isn't FUD. You, Doug, have to prove that it is, because you accused it of being FUD. By your logic, I can prove that you are a piece of cheddar cheese. I will simply assert that you are a piece of cheddar cheese. You might respond by making a surprisingly lucid (for a piece of cheddar) argument that you are a sentient being. To this I will respond "You idiot, proving that you are a sentient being doesn't mean you can't be a piece of cheddar." QED. Since you are too lazy to post the wikipedia link, please allow me: http://en.wikipedia.org/wiki/Fear%2C_uncertainty_and_doubt According to that definition, FUD is "a sales or marketing strategy of disseminating negative (and vague) information on a competitor's product." Even if the FAQ could, by a stretch of the imagination, be considered a sales or marketing strategy, you'd be hard-pressed to find evidence of it disseminating negative information on a competitor's product. Hence, it's not FUD. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
On Sat, 2006-11-11 at 23:18 -0800, Doug wrote: > Michael Hobbs wrote: > > I think the colon could be omitted from every type of compound > > statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything? > > > > Thanks, > > - Mike > > It is a very good idea as the colon is technically redundant (not > necessary for parsing, aside from one liners) and actually hurts > readability (and writeability). The "evidence" people cite for the > advantage of using a colon is research done by users of the ABC > language, python's predecessor. They forget that A) that was like 20 > years ago, Research being old does not automatically invalidate it. Old research is invalidated by newer research that invalidates it. > B) the language was designed for children, http://www.cwi.nl/archive/projects/abc.html does not mention children: "Originally intended as a language for beginners, it has evolved into a powerful tool for beginners and experts alike." > and C) the > keywords in ABC are IN ALL CAPS LIKE THIS (hurting readability and > writeability) and thus adding a colon obviously helps restore some > readability for users in that case but not in python's. So what are you saying? In a programming language that doesn't use all caps keywords, adding colons to block-beginning lines hurts readability, or it doesn't add any readability? In any case, that's an assertion that should be backed up by citing relevant research. > However, python is far too old to accept any fundamental changes to > syntax at this point. The source code for Python is openly available. If you are so convinced of the added readability from removing the colons, do the world a favor and make the necessary change, or hire somebody to make the change, to Python. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: jython's future (was: Python development time is faster.)
On Mon, 2006-11-13 at 18:34 +0100, Stefan Behnel wrote: > Honestly, how many important Python modules do still run on 2.2? InformixDB still compiles on 2.2 except when I accidentally temporarily break backwards compatibility. Of course it's a matter of opinion whether it qualifies as an important module. ;-) -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python for me?
On Mon, 2006-11-13 at 10:14 -0800, Dan Lenski wrote: > lennart wrote: > > So i ask myself is python the language I'm looking for? > > Yep! Python is very much a jack-of-all-trades language. I'll run the risk of being nitpicky, but the full phrase is "Jack of all trades, master of none," which doesn't do Python justice. Python is a master of all trades! But I agree with Dan's sentiment, Python is definitely the language you're looking for. -Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob | datetime question
On Tue, 2006-11-14 at 09:33 -0600, Kevin Kelley wrote: > import time > FORMAT='%Y%m%d' > > time.strftime(FORMAT,time.gmtime(time.time()+8380800)) > output = '20070219' While the above works, the following variation using datetime is more readable: >>> import datetime >>> someday = datetime.date.today() + datetime.timedelta(days=97) >>> print someday.strftime("%Y%m%d") 20070219 -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Yield
On Wed, 2006-11-15 at 09:13 -0800, Mateuszk87 wrote: > Hi. > > may someone explain "yield" function, please. how does it actually work > and when do you use it? [There is probably a much better explanation of this somewhere on the net already, but I feel like writing this out myself.] "yield" is a keyword. In simple terms, if "yield" appears inside a function, the function becomes a generator that can return multiple results. Consider the following trivial example of a function that calculates the elements of some sequence and prints each one. def squares(n): for i in range(n): print i**2 Now suppose it turns out that in addition to--or instead of--printing the elements of this sequence, the caller wants to do something different with them. You could handle this by building a list, and return the list to the caller to loop over and operate on as they choose. But if the list is very big, that's not very memory-efficient if the caller only needs to operate on one element at a time. This is where yield comes in. If you write this: def squares(n): for i in range(n): yield i**2 squares is now a generator function. If you call squares(100), it won't calculate any sequence elements immediately. It will instead return an iterator the caller can loop over: for el in squares(100): print el # or do anything else the caller decides The beauty of this is that you achieve physical separation between generating elements of a sequence and using them. The generator function only cares about how to produce the elements, and the caller only cares about how to use them. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Yield
On Thu, 2006-11-16 at 07:32 -0800, Danny Colligan wrote: > Carsten mentioned that generators are more memory-efficient to use when > dealing with large numbers of objects. Is this the main advantage of > using generators? Also, in what other novel ways are generators used > that are clearly superior to alternatives? The memory efficiency is definitely a major advantage. Generators allow you to efficiently produce, manipulate, and consume sequences of arbitrary length. The length of the sequence could even be potentially infinite, which is impossible to handle when you're working with actual lists. The memory efficiency aside, it's more elegant to write something like this: def squares(n): for i in range(n): yield i**2 than something like this: def squares(n): result = [] for i in range(n): result.append(i**2) return result -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Yield
On Thu, 2006-11-16 at 08:09 -0800, Danny Colligan wrote: > > The more trivial the example, the harder it is to see the advantage. > > I absoultely agree. Thanks for pointing me out to some real-world > code. However, the function you pointed me to is not a generator > (there is no yield statement... it just returns the entire list of > primes). A generator version would be: > > >>> def primes(n): > ... if n<2: yield [] > ... s=range(3,n+1,2) > ... mroot = n ** 0.5 > ... half=(n+1)/2-1 > ... i=0 > ... m=3 > ... while m <= mroot: > ... if s[i]: > ... j=(m*m-3)/2 > ... s[j]=0 > ... while j ... s[j]=0 > ... j+=m > ... i=i+1 > ... m=2*i+3 > ... yield 2 > ... for x in s: > ... if x: yield x Not quite: >>> x = primes(1) >>> x.next() [] >>> x.next() 2 >>> x.next() Traceback (most recent call last): File "", line 1, in ? StopIteration To handle n<2 correctly, you have to "return" instead of "yield []". >>> x = primes(1) >>> x.next() Traceback (most recent call last): File "", line 1, in ? StopIteration -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: atexit.register does not return the registered function. IMHO, it should.
On Thu, 2006-11-16 at 08:03 -0800, [EMAIL PROTECTED] wrote: > @atexit.register > def goodbye(): > print "Goodbye, terminating..." > > > However, there is one fundamental problem with this: atexit.register() > returns None. Since the above code corresponds to:: > > > def goodbye(): > print "Goodbye, terminating..." > goodbye = atexit.register(goodbye) > > the code registers goodbye but right after it binds goodbye to None! While it wouldn't hurt to have atexit.register return the function it registered, this "problem" is only a problem if you wish to call the function manually, since atexit already registered the reference to the intended function before your reference to it gets rebound to None. Normally one would register a function with atexit precisely because they don't want to call it manually. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: re.compile() doesn't work under Windows?
On Thu, 2006-08-31 at 17:38, ddtl wrote: > Hello everybody. > > My script uses re.compile() function, and while it rans without errors > under Linux, when I ran that script under Windows I get the following > error: > > Traceback (most recent call last): > File "C:\a\projects\re.py", line 4, in ? > import re > File "C:\a\projects\re.py", line 95, in ? > main() > File "C:\a\projects\re.py", line 37, in main > s_exp = re.compile(op['-s']) > AttributeError: 'module' object has no attribute 'compile' > > What is the problem here? re module is installed and is on the path - > for example, the following code works and doesn't cause any errors: > > import re > re.compile('a') > > What else could cause such an error? Your script is called re, so "import re" is making the script import itself instead of the re module from the library. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: REQ: Java/J2EE Developer 10 Months
On Fri, 2006-09-15 at 14:41, Steve Holden wrote: > [EMAIL PROTECTED] wrote: > [...] > > Skill: > > > > > > *Java, 2 year UNIX - HP / Solaris, 2 yrs OOA+D, Corba, Perl, XML, UML. > > *Java dev experience, Swing, JPS, 2 years of OOA+D. > > Clearly not spam, since the guy is so in touch with the readership of > this group ... sigh ... is it just me, or is this person an idiot? Yes, he is an idiot. Good call on CC'ing your assessment to him. :) -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Python/MySQL problem on Windows
On Wed, 2006-09-20 at 16:37, Eric Smith wrote: > I'm trying to use Python 2.4.3 and pywin32-209 to access a MySQL > database on Windows Server 2003 Standard Edition, and not having much > luck. It seems like parts of the MySQLdb module are not getting loaded > correctly, but no error message is given during the import, even if I > give a "-vv" on the command line. > > I'm trying to do: > > import MySQLdb > db = MySQLdb.connection (db="database", user="user", passwd="password") What happens if you use connect(...) instead of connection(...)? -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested Looping SQL Querys
On Thu, 2006-09-21 at 01:12, Dennis Lee Bieber wrote: > On Wed, 20 Sep 2006 13:21:54 -0400, Steve Holden <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > .execute() is a cursor method, not a connection method. Some DB API > > modules do implement it as a connection method, but that makes it > > impossible for several cursors to share the same connection (which is > > allowed by some modules). > > > It struck me that the original wasn't using a cursor just after the > messages posted. It doesn't look like the OP is using anything even remotely DB-API compliant: """ import cmi import hermes conn = hermes.db() pubID=cgiForm.getvalue('pubID') pubName=cgiForm.getvalue('pubName','Unknown Publication') sqlcheck1 = "SELECT pub_type FROM medusa.cmi_publication WHERE pub_id = '"+pubID+"'" overseas1 = conn.query(sqlcheck1) pubType = cmi.fetch_rows(overseas1) """ hermes is apparently some wrapper that magically can connect to a well-known database (via the argumentless db()) call. Who knows what kind of animal the 'conn' object is that comes out of that db() call. Apparently it's an object with a query() method that returns something like a cursor that can be passed into cmi.fetch_rows(). At this point I wonder why the responsibility of fetching rows is in a module separate from the responsibility of establishing a database connection. Legacy code, indeed. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Isn't bool __invert__ behaviour "strange"?
On Fri, 2006-09-22 at 11:25, Saizan wrote: > Bjoern Schliessmann wrote: > > Saizan wrote: > > > > > Why subclassing bool from int either __invert__ or __neg__ haven't > > > been overrided to produce a boolean negation? > > > > I wonder what -True or -False should evaluate to. > Well in boolean notation -True == False and -False == True, actually > you may prefer ¬ or a line over the term, but since there's no such > operator in python [...] It's called "not": >>> not True False >>> not False True -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Need compile python code
On 23 Sep 2006 12:24:58 -0700, mistral wrote > No, something is wrong there. what I need is just compile one python > file which will generate html page, with parameters: > "exec" "python" "-O" "$0" "$@" This is not a python script. It appears to be a Unix shell script that calls a python script. Maybe it would help if you told us exactly what you're trying to accomplish and why you think you need to "compile python code". -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: QuoteSQL
On Tue, 2006-09-26 at 07:08, Lawrence D'Oliveiro wrote: > So yes, there should be two separate functions, one for escaping > non-wildcard specials, and one for escaping wildcards. > > > You only need the first one, since every database interface that > > follows PEP 249. > > You still need the second one, in instances like the QuoteSQLList example I > gave earlier. "Need" is a strong word unless something like the following doesn't work for some reason: cur.execute("select * from people where last_name in (%s,%s,%s)", (name1, name2, name3) ) -Carsten -- http://mail.python.org/mailman/listinfo/python-list
[ANN] InformixDB-2.3 released
I am pleased to announce a new release of InformixDB, the DB-API 2.0 module for connecting to IBM Informix database engines. Changes since version 2.2: - Allow parameter list for executemany() to be arbitrary iterable objects. - .prepare() method and .command attribute for explicitly prepared statements - Python 2.5 compatibility - Bug fixes: * Rare crashes caused by missing error check in DESCRIBE step. * Inconsistent UDT input binding caused SQLCODE -1820 in bulk insert (executemany) if UDT contents went back and forth across 32K size boundary or between null and non-null. * EXECUTE PROCEDURE erroneously attempted to open a results cursor for procedures that don't return results. * Date columns were read incorrectly on 64 bit platforms due to mixup of int4 versus long. Downloads and info at http://informixdb.sourceforge.net Best regards, Carsten Haese -- http://mail.python.org/mailman/listinfo/python-list
Re: Instantiating an object when the type is only known at runtime
On Tue, 2006-10-03 at 18:19, Samuel wrote: > Thanks, that's what I was looking for. > > > >>> m = __import__( "StringIO" ) > > >>> x = getattr( m, "StringIO" )() > > >>> x > > > > >>> > > For the records: If the module is already loaded, this also works: > > if my_type_is_not_yet_loaded: > module = __import__(type) > obj= getattr(module, type) > else: > obj= globals().get(type) > resource = obj(my_arg1, my_arg2) You seem to be under the impression that importing an already imported module is a hideously expensive operation that must be avoided at all costs. It's not. If you import an already imported module, python simply returns the module object from sys.modules without executing any of the module's code. Your code will be much easier to read if you eliminate the "my_type_is_not_yet_loaded" check, whatever that may be under the hood, and always perform the __import__. It's also likely to be at least as fast, but I couldn't run a timing comparison even if I wanted to because you didn't post working code. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimal() instead of float?
On Fri, 2006-11-17 at 16:51 -0500, Michael B. Trausch wrote: > [...] > Let's say that I want to work with the latitude 33.6907570. In > Python, that number can not be stored exactly without the aid of > decimal.Decimal(). > > >>> 33.6907570 > 33.6907568 You say that like it's Python's fault. Can this number be stored *exactly* in C? -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimal() instead of float?
On Fri, 2006-11-17 at 16:51 -0500, Michael B. Trausch wrote: > On Fri, 2006-11-17 at 21:25 +0100, Fredrik Lundh wrote: > > > Some of the lat/long pairs that I have used seem to come out fine, but > > > some do not. Because the mathmatics used with them involve complex > > > equations when determining distance and the like, any error gets > > > massively compounded before a final result is evident. > > > > sorry, but I don't think you have the slightest idea what you're doing, > > really. > > > > Sure, I do. Let's say that I want to work with the latitude > 33.6907570. In Python, that number can not be stored exactly without > the aid of decimal.Decimal(). > > >>> 33.6907570 > 33.6907568 > >>> > > As you can see, it loses accuracy after the 6th decimal place. That's > not good enough: I have 8 numbers that need to be exact, and I am > only getting six. Really? >>> x = 33.6907570 >>> for i in range(7,16): print "%.*f" % (i,x) ... 33.6907570 33.69075700 33.690757000 33.690757 33.6907570 33.69075700 33.690757000 33.690757 33.6907568 Looks to me like you're getting, uh, 14 decimal digits, for a total of 16 significant digits. What kinds of operations are you performing that compound this error by seven orders of magnitude? -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance from builtin list and override of methods.
On Mon, 2006-11-27 at 19:14 +, OKB (not okblacke) wrote: > Duncan Booth wrote: > > >> And is there a mechanism in Python that will allow me to override > >> the operators of a class, for all its occurrences, even the ones > >> implemented on C built-in objects? > > > > No. > > For what it's worth, which is undoubtedly nothing, Correct. > this is > something that I think needs to change. All this talk about new-style > classes and class-type unification is empty words if you can't override > anything on any type without having to know whether it's written in C or > Python. Duncan's "No" response was not referring to overriding in general, it was referring to the OP's original question which amounted to "Can I affect the behavior of method Z by overriding methods X and Y". The inability to influence a method by overriding completely different methods has nothing to do with whether that method is implemented in C or Python; it has to with whether the method in question calls the overridden methods, and in general it won't. You can change the behavior of a list's sort method by overriding sort. You can't change the behavior of sort by overriding __getitem__ and __setitem__, because sort does not call __getitem__ or __setitem__. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] InformixDB-2.4 released
I am pleased to announce a new release of InformixDB, the DB-API 2.0 module for connecting to IBM Informix database engines. The list of changes since version 2.3 is short but sweet: - Implement 'named' parameter style to optionally bind query parameters by name - Implement option to retrieve opaque types in their binary representation Downloads and info at http://informixdb.sourceforge.net Best regards, Carsten Haese -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On Mon, 2006-12-04 at 01:04 -0800, Russ wrote: > Robert Kern wrote: > > > Nothing is going to happen until you do one of these two things. Being more > > rude > > (and yes, you are being incredibly rude and insulting) won't move things > > along. > > I re-read the thread, and I don't see anywhere where I was rude Please allow me to break it down for you: Your first reply on this thread, or second message, said: """ Now, that [submitting a patch that fixes the problem] would be rather silly. I would have to familiarize myself with the code for the Python interpreter, then send a patch to the maintainers (and hope they notice it in their inboxes), while the maintainers themselves could probably "fix" the problem in two minutes flat. No thanks! My suggestion is trivial to implement and would benefit every Python programmer (even if only slightly), so I don't think it is too much to ask for. """ You may not have meant this to be rude, but it does come off as rude and arrogant, and I'll explain to you why: In your first post you stated that the feature seems like a no-brainer to you. That implies to the reader that you might have the necessary skill to implement the feature yourself, hence Robert's suggestion to submit a patch was, in the context you gave yourself, neither unreasonable nor silly. I can see how your calling a reasonable suggestion by a valuable community member "silly" would be construed as rude and arrogant. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On Mon, 2006-12-04 at 08:49 -0800, [EMAIL PROTECTED] wrote: > Carsten Haese wrote: > > On Mon, 2006-12-04 at 01:04 -0800, Russ wrote: > > > Robert Kern wrote: > > > > > > > Nothing is going to happen until you do one of these two things. Being > > > > more rude > > > > (and yes, you are being incredibly rude and insulting) won't move > > > > things along. > > > > > > I re-read the thread, and I don't see anywhere where I was rude > > > > Please allow me to break it down for you: > > > > Your first reply on this thread, or second message, said: > > > > """ > > Now, that [submitting a patch that fixes the problem] would be rather > > silly. I would have to familiarize myself > > with the code for the Python interpreter, then send a patch to the > > maintainers (and hope they notice it in their inboxes), while the > > maintainers themselves could probably "fix" the problem in two minutes > > flat. No thanks! > > > > My suggestion is trivial to implement and would benefit every Python > > programmer (even if only slightly), so I don't think it is too much to > > ask for. > > """ > > > > You may not have meant this to be rude, but it does come off as rude and > > arrogant, and I'll explain to you why: In your first post you stated > > that the feature seems like a no-brainer to you. That implies to the > > reader that you might have the necessary skill to implement the feature > > yourself, hence Robert's suggestion to submit a patch was, in the > > context you gave yourself, neither unreasonable nor silly. I can see how > > your calling a reasonable suggestion by a valuable community member > > "silly" would be construed as rude and arrogant. > > Thanks for explaining why the OP was rude. Having been > reading and listening to english for only a few decades > probably, I am sure the OP (and me too!) appreciates your > explanation of rudeness. It was really hard for me to see it > until you explained it so well. The great thing about c.l.p. is > how much one learns about non-Python things here. > (oops, I hope I wasn't rude by saying there were non-Python > things? I didn't mean to diminish Python in any way.) > > Russ, > Please rememer that learning Python is not done overnight -- > there are many different levels of knowlage and only the > most elite Pythonists have reached True Understanding. > > Since there are many things you don't understand, it is > best you (and me too!) do not make suggrestions publically. > Infidels could read them and inplying that Python is not > perfect and you will undermine the spritual growth of > many other newbies.. Such dangerous sugggestions > should be made privately at the alter of Sourceforge, with > a lot of deep self-reflection and piety. > > Until you achive greater understanding it is best if in public > you make sure that you write with the following in mind: > Python is perfect > Perl sucks > Static typing sucks > Python is faster than C > Quoting frequently from the holy Zen of Python is also > helpful. Please remember that many regulars here are > members of the holy priesthood because they have spent > many years studying the Python scriptures. Be as circumspect > in addressing them as you would be a medival knight or > Japanese samurai. Only by following their guidance with > complete devoutness and faith will you be able to achive > the deepest level of Python appreciation. > > Hope this helps. My sarcasm meter just exploded. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
On Mon, 2006-12-04 at 14:03 -0800, king kikapu wrote: > I recap: if i put only functions declarations on a .py file, like > these: > def A(): print "a" > def B(): print "b" > def C(): print "c" > > and run the program, nothing happens, nothing executed. Nothing *visible* happens. The "def" statements *do* get executed. Executing the statement def A(): print "a" does the following, roughly, modulo irrelevant implementation details: * The function body gets compiled into byte code (but not executed). * A callable object with the byte code for the compiled function body is constructed. * The thusly constructed callable object is bound to the name A in your current namespace. So, a lot of stuff happens when the interpreter executes a def statement, but that stuff is not visible to you. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
On Mon, 2006-12-04 at 23:44 +0100, Fredrik Lundh wrote: > Carsten Haese wrote: > > > * The function body gets compiled into byte code (but not executed). > > careful: when you get as far as executing the "def" statement, the > function body has already been compiled. the byte code for the function > is stored as a module-level constant: You are, as always, correct, but I deliberately hid this detail inside the "roughly, modulo irrelevant implementation details" disclaimer in an attempt of causing the OP the smallest possible amount of confusion. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert a function into generator?
On Wed, 2006-12-06 at 17:33 +0100, Schüle Daniel wrote: > def permute3gen(lst): > lenlst = len(lst) > def permute(perm, level): > if level == 1: > yield perm > return # not sure return without a value is allowed, > theoretically it could be replaces with if/else block > for i in lst: > if i not in perm: > permute(perm + (i,), level - 1) ##1## > for item in lst: > yield permute((item,), lenlst) # makes generator from the outer > function too ##2## Your only problem is in knowing what to do with recursively invoked sub-generators. You have two such invocations, which I marked above with ##1## and ##2##, and neither one is handled correctly. In ##1##, you construct a sub-generator and simply discard it. In ##2##, you construct a sub-generator, and yield it (instead of yielding its elements). In neither case do you actually consume any of the elements that the sub-generators are prepared to produce. To usefully invoke a sub-generator, you need to consume it (i.e. iterate over it) and yield whatever it produces. Hope this helps, Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Non greedy regex
On Thu, 2006-12-14 at 06:45 -0800, [EMAIL PROTECTED] wrote: > Can someone please explain why these expressions both produce the same > result? Surely this means that non-greedy regex does not work? > > print re.sub( 'a.*b', '', 'ababc' ) > > gives: 'c' > > Understandable. But > > print re.sub( 'a.*?b', '', 'ababc' ) > > gives: 'c' > > NOT, understandable. Surely the answer should be: 'abc' You didn't tell re.sub to only substitute the first occurrence of the pattern. It non-greedily matches two occurrences of 'ab' and replaces each of them with ''. Try replacing with some non-empty string instead to observe the difference between the two behaviors. -Carsten -- http://mail.python.org/mailman/listinfo/python-list