itools 0.20.4 released

2008-02-07 Thread J. David Ibáñez
itools is a Python library, it groups a number of packages into a single
meta-package for easier development and deployment:

   itools.catalog  itools.i18n itools.uri
   itools.csv  itools.ical itools.vfs
   itools.datatypesitools.odf  itools.web
   itools.gettext  itools.pdf  itools.workflow
   itools.git  itools.rest itools.xliff
   itools.handlers itools.rss  itools.xml
   itools.html itools.stl
   itools.http itools.tmx

The isetup-doc.py script has been removed, now we use epydoc [1,2]
for the automatically generated documentation.

The itools.http and itools.web packages have seen important fixes,
like better support for cookies and better handling of bad requests.

The itools.xml and itools.html packages now correctly raise an
exception when a close tag is missing at the end of the file.


[1] http://epydoc.sourceforge.net/
[2] http://download.ikaaro.org/doc/itools-reference/


Resources
-

Download
http://download.ikaaro.org/itools/itools-0.20.4.tar.gz
http://download.ikaaro.org/itools/itools-0.20.4.win32-py2.5.exe
http://download.ikaaro.org/itools/itools-0.20.4.win32-py2.4.exe

Home
http://www.ikaaro.org/itools

Mailing list
http://mail.ikaaro.org/mailman/listinfo/itools

Bug Tracker
http://bugs.ikaaro.org/



-- 
J. David Ibáñez
Itaapy http://www.itaapy.com Tel +33 (0)1 42 23 67 45
9 rue Darwin, 75018 Paris  Fax +33 (0)1 53 28 27 88
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


[ANN] Leipzig Python User Group - Meeting, February 12, 2008, 08:00pm

2008-02-07 Thread Mike Müller
=== Leipzig Python User Group ===

We will meet on Tuesday, February 12 at 8:00 pm at the training
center of Python Academy in Leipzig, Germany
( http://www.python-academy.com/center/find.html ).

Maik Derstappen will give a presentation about Plone.

Food and soft drinks are provided. Please send a short
confirmation mail to [EMAIL PROTECTED], so we can prepare
appropriately.

Everybody who uses Python, plans to do so or is interested in
learning more about the language is encouraged to participate.

While the meeting language will be mainly German, we will provide
English translation if needed.

Current information about the meetings are at
http://www.python-academy.com/user-group .

Mike



== Leipzig Python User Group ===

Wir treffen uns am Dienstag, 12.02.2008 um 20:00 Uhr
im Schulungszentrum der Python Academy in Leipzig
( http://www.python-academy.de/Schulungszentrum/anfahrt.html ).

Maik Derstappen wird einen Vortrag über Plone halten.

Für das leibliche Wohl wird gesorgt. Eine Anmeldung unter
[EMAIL PROTECTED] wäre nett, damit wir genug Essen
besorgen können.

Willkommen ist jeder, der Interesse an Python hat, die Sprache
bereits nutzt oder nutzen möchte.

Aktuelle Informationen zu den Treffen sind unter
http://www.python-academy.de/User-Group zu finden.

Viele Grüße
Mike

-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ANN: ConfigObj 4.5.1 and validate 0.3.1

2008-02-07 Thread Fuzzyman
After one year and two days since the last release, there is a new
release of ConfigObj.

* ConfigObj 4.5.1 http://www.voidspace.org.uk/python/configobj.html
* Validate 0.3.1 http://www.voidspace.org.uk/python/validate.html

This release adds a few new features, plus has several bugfixes and
minor performance improvements.
Thanks to all those who gave feedback, reported bugs and provided
patches.


What are ConfigObj and Validate?
=

**ConfigObj** is a simple to use but powerful configuration file
management library.
Features include:

* Nested sections to any depth
* Unicode support
* List and multiline values
* Integrated with a powerful validation system

- including automatic type checking/conversion
- repeated sections
- and allowing default values

* All comments in a file are preserved when writing
* The order of keys/sections is preserved
* A powerful unrepr mode for storing basic datatypes

**validate** is the module (optional) used for config file validation
and type marshalling. It
can be used outside of ConfigObj for matching string values against a
text specification which
also does type conversion.


Changes in ConfigObj 4.5.1


Distribution updated to include version 0.3.1 of validate. This means
that
Unicode configspecs now work.

ConfigObj will now guarantee that files will be written terminated
with a
newline.

ConfigObj will no longer attempt to import the ``validate`` module,
until/unless
you call ``ConfigObj.validate`` with ``preserve_errors=True``. This
makes it
faster to import.

New methods ``restore_default`` and ``restore_defaults``.
``restore_default``
resets an entry to its default value (and returns that value).
``restore_defaults``
resets all entries to their default value. It doesn't modify entries
without a
default value. You must have validated a ConfigObj (which populates
the
``default_values`` dictionary) before calling these methods.

BUGFIX: Proper quoting of keys, values and list values that contain
hashes
(when writing).  When ``list_values=False``, values containing hashes
are
triple quoted.

Added the ``reload`` method. This reloads a ConfigObj from file. If
the filename
attribute is not set then a ``ReloadError`` (a new exception
inheriting from
``IOError``) is raised.

BUGFIX: Files are read in with 'rb' mode, so that native/non-native
line endings work!

Minor efficiency improvement in ``unrepr`` mode.

Added missing docstrings for some overridden dictionary methods.

Added the ``reset`` method. This restores a ConfigObj to a freshly
created state.

Removed old CHANGELOG file.


Changes in Validate 0.3.1
==

BUGFIX: Unicode checks no longer broken.

Improved performance with a parse cache.

New ``get_default_value`` method. Given a check it returns the default
value (converted to the correct type) or raises a ``KeyError`` if the
check doesn't specify a default.

Added 'tuple' check and corresponding 'is_tuple' function (which
always returns a tuple).

BUGFIX: A quoted 'None' as a default value is no longer treated as
None,
but as the string 'None'.

BUGFIX: We weren't unquoting keyword arguments of length two, so an
empty string didn't work as a default.

BUGFIX: Strings no longer pass the 'is_list' check. Additionally, the
list checks always return lists.

A couple of documentation bug fixes.

Removed CHANGELOG from module.


Michael Foord
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: beginner question, function returning object.

2008-02-07 Thread bambam
Second try (correction)

I started with ths:
 --
def open_pipe():
pipe=PIPE()
print pipe
return pipe

 pipe=open_pipe()
pipe.parent = self.parent
print pipe
 --
 It didn't do what I wanted: when I printed the pipe the second time it was
 not the same object as the first time.

 So I changed it to this:
def open_pipe(pipe):
pipe=PIPE()
print pipe

 pipe = None
open_pipe(pipe)
pipe.parent = self.parent
print pipe

 It still doesn't do what I wanted: I can't assign the parent property
 because pipe type is None.

 I'm not sure enough of what I am doing to tell if I have another error in 
my
 code causing the problem. Is either of these examples supposed to work as
 shown? Is it clear that either example is obviously wrong?





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread bearophileHUGS
Paul Rubin:
 I like the suggestion, except it should be
  port = int(sys.argv.get(1, '8000'))
 one could imagine your example going wrong in a protocol where 0 is
 a valid port number.

I think a high-level language like Python must have boolean operators
(or and not) that behave in a much more clean way, with a simpler
semantics. That is they have to return only true or false. Otherwise
they are just a source of bugs and confusion. This is a change fit for
Python 3.
That trick with or/and may look good for Perl, but it's unfit for a
language that tries to be clear, readable from people that don't know
it much, and good to learn to program. Python has now the if-then
expression too that is more clear.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner question, function returning object.

2008-02-07 Thread Marc 'BlackJack' Rintsch
On Thu, 07 Feb 2008 19:14:54 +1100, bambam wrote:

 I started with ths:
  --
 def open_pipe():
 pipe=PIPE()
 print pipe
 return pipe
 
  pipe=open_pipe()
 pipe.parent = self.parent
 print pipe
  --
  It didn't do what I wanted: when I printed the pipe the second time it was
  not the same object as the first time.

Please post actual minimal code that reproduces the problem and a better
description of what you get and what you expected instead.

What is `PIPE` and where does `self` come from?  What are the too
``print``\s printing that makes you think `pipe` isn't bound to the same
object?

  So I changed it to this:
 def open_pipe(pipe):
 pipe=PIPE()
 print pipe
 
  pipe = None
 open_pipe(pipe)
 pipe.parent = self.parent
 print pipe
 
  It still doesn't do what I wanted: I can't assign the parent property
  because pipe type is None.

Yes because in `open_pipe()` you bind a new object to the local name
`pipe` which of course has no effect on the binding of the name `pipe` in
the callers namespace.

 I'm not sure enough of what I am doing to tell if I have another error in 
 my code causing the problem. Is either of these examples supposed to work
 as shown? Is it clear that either example is obviously wrong?

The second is wrong.  The first should work if `self` and `PIPE` are bound
to appropriate objects.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting all user defined attributes of a class

2008-02-07 Thread grflanagan
On Feb 6, 11:07 pm, Amit Gupta [EMAIL PROTECTED] wrote:
 Hi

 How do I get user defined attributes of a class? e.g

 Class A(object) :
   self.x = 1
 --

 I want something like:
   for userattrib in A.getAllUserAttribute() :
 print userattrib



class Meta(type):

def __init__(cls, name, bases, attrs):
super(Meta, cls).__init__(name, bases, attrs)
cls._attrs = attrs.keys()


class Base(object):
__metaclass__ = Meta

def getmembers(self):
return [k for k in self.__dict__ if k not in self._attrs]

class MyObj(Base):

def __init__(self):
self.a = 1
self.b = 2

obj = MyObj()

print obj.getmembers()

['a', 'b']

setattr(obj, 'c', 3)

print obj.getmembers()

['a', 'c', 'b']

HTH

Gerard
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
 Paul Rubin:
 I like the suggestion, except it should be
  port = int(sys.argv.get(1, '8000'))
 one could imagine your example going wrong in a protocol where 0 is
 a valid port number.
 
 I think a high-level language like Python must have boolean operators
 (or and not) that behave in a much more clean way, with a simpler
 semantics. That is they have to return only true or false. Otherwise
 they are just a source of bugs and confusion. This is a change fit for
 Python 3.

Conditional expressions have clear semantics.

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code block function syntax, anonymous functions decorator

2008-02-07 Thread Diez B. Roggisch
Jean-Paul Calderone schrieb:
 On Wed, 06 Feb 2008 23:59:27 +0100, Diez B. Roggisch 
 [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] schrieb:
 def run3( block ):
for _ in range( 3 ):
   block()

 run3():
normal_suite()

 Introduces new syntax; arbitrary functions can follow 'colon'.

 Maintains readability, meaning is consistent.

 Equivalent to:

 def run3( block ):
for _ in range( 3 ):
   block()

 @run3
 def anonfunc():
normal_suite()

 Simplification in cases in which decorators are use often.

 This is non-sensical - how do you invoke anonfunc? They would all bind
 to the same name, run3. Or to no name as all, as your spec lacks that.
 
 As he said, the decorator version is the _equivalent_ to the syntax he
 was proposing.  The point isn't to decorate the function, so perhaps he
 shouldn't have used decorator syntax, but instead:
 
def anonfunc():
normal_suite()
run3(anonfunc)
del anonfunc
 
 So it's not non-sensical.  It's a request for a piece of syntax.
 

 Besides, it's butt-ugly IMHO. But taste comes after proper definition...
 
 It's properly defined.  Not that I'm endorsing this or anything.  I'd
 rather not see half-assed syntax proposals at all, even if they're super
 great (and some of the syntax that's made it into Python is much worse
 than this).

Yeah, I missed somehow that the decorator doesn't actually return anything.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to use .NET DLL from Python

2008-02-07 Thread Fuzzyman


Luis M. González wrote:
 On 6 feb, 21:17, Fuzzyman [EMAIL PROTECTED] wrote:
  On Feb 6, 9:59 pm, Luis M. Gonz�lez [EMAIL PROTECTED] wrote:
 
   On Feb 6, 6:27 pm, Huayang Xia [EMAIL PROTECTED] wrote:
 
Hello All,
 
I have several .NET DLL (I have no source code for them), is there
anyway to use them from python instead of from C#.
 
Thanks,
Huayang
 
   I used to put my .dll files into the .DLL folder, so I could simply
   import them as I would with any other python module.
   But since I started using Ironpython 2.0 Alpha* this doesn't work
   anymore...
   Any hint?
 
  The rule is probably still that the DLLs must be in a directory on
  sys.path for the interpreter to find them. Try adding the directory
  containing the assemblies to sys.path and see if you can add
  references to them.
 
  Michael Foordhttp://www.manning.com/foord
 
 
 
   Luis

 I tried adding the directory to sys.path.
 Still not working...

  import sys
  sys.path.append('C:\Documents and 
  Settings\luismg\Escritorio\IronPython-2.0A
 8\DLLs')
  from ClassLibrary1 import *
 Traceback (most recent call last):
   File , line unknown, in ##235
   File , line unknown, in _stub_##2
 ImportError: No module named ClassLibrary1

You need to add references to assemblies before you can import from
the namespaces they contain.

import clr
clr.AddReference('ClassLibrary1')

HTH

Fuzzyman
http://www.manning.com/foord

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: beginner question, function returning object.

2008-02-07 Thread Steven D'Aprano
On Thu, 07 Feb 2008 19:14:54 +1100, bambam wrote:

 Second try (correction)
 
 I started with ths:
  --
 def open_pipe():
 pipe=PIPE()
 print pipe
 return pipe

What's PIPE() do?


 pipe=open_pipe()

(Extraneous space removed.)

 pipe.parent = self.parent

What's self? What's it do? What's self.parent and what does it do?

 print pipe
  --
  It didn't do what I wanted: when I printed the pipe the second time it
  was not the same object as the first time.

How do you know? What makes you think they are different objects?


 
  So I changed it to this:
 def open_pipe(pipe):
 pipe=PIPE()
 print pipe
 
  pipe = None

Again with the extraneous space.

 open_pipe(pipe)

This can't possibly work. What you are doing is this:

(1)  set the name 'pipe' to None
(2)  call the function open_pipe() with None as the argument
(3)  which reassigns the *inner* variable 'pipe' to the result of PIPE(),
but doesn't do anything to the *global* variable 'pipe'
(4)  open_pipe() now returns None, which doesn't get used

So as you can see, the global 'pipe' starts off as None, and then nothing 
happens to it, so it stays None.

 pipe.parent = self.parent
 print pipe
 
  It still doesn't do what I wanted: I can't assign the parent property
  because pipe type is None.

  I'm not sure enough of what I am doing to tell if I have another error
  in my
  code causing the problem. Is either of these examples supposed to work
  as shown? Is it clear that either example is obviously wrong?


Your first attempt was almost certainly the correct way to try to do what 
you want. I suspect that your function PIPE() is broken.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: loading dictionary from a file

2008-02-07 Thread Fuzzyman


Amit Gupta wrote:
 Need a python trick, if it exists:

 I have a file that stores key, value in following format
 --
 v1 : k1,
 v2 : k2
 --

 Is there a way to directly load this file as dictionary in python. I
 could do (foreach line in file, split by : and then do dictionary
 insert). Wondering, if some python built-in function can just read a
 valid dictionary-file and load it?


If you change the format slightly you could use ConfgiObj 
http://www.voidspace.org.uk/python/configobj.html .

key = value
key2 = value2

Fuzzyman
http://www.voidspace.org.uk/python/weblog/index.shtml



 Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Tim Golden
Denis Bilenko wrote:
 Why does list have no 'get' method with exactly the same semantics as
 dict's get,
 that is return an element if there is one, but do NOT raise
 an exception if there is not.:
 
 def get(self, item, default = None):
 try:
 return self[item]
 except IndexError:
 return default
 
 It is often desirable, for example, when one uses the easiest
 command-line options parsing - based on absolute positions:

Dodging your question slightly (and at the risk of teaching
my grandmother to suck eggs) I sometimes use this idiom for
checking params. Obviously it only goes so far, but it's
fairly compact:

Noddy example code
import os, sys

if __name__ == '__main__':
   ARGS = None, DEV
   filename, db = \
 (j or i for i, j in map (None, ARGS, sys.argv[1:]))

   print sys.argv
   print filename, db

/code

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding properties to an instance

2008-02-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 On Feb 6, 11:09 pm, [EMAIL PROTECTED]
 [EMAIL PROTECTED] wrote:
 While this is technically possible (I tried a couple years ago), it
 requires hacking the __getattribute__ method, which is something I
 would not recommand, not only because it can be tricky, but mostly
 because this is a very critical path wrt/ perfs.  (IIRC it also
 required using custom descriptors, but I'm not really sure about this
 last point).
 
 Performance is pretty important for the class I'm designing so I think
 __getattribute__ is probably out. The computed properties are only
 infrequently accessed, but using __getattribute__ slows everything
 down, right?

Indeed - it *is* the attribute lookup mechanism. Better to leave it alone.

 Before new-style classes, we used the __getattr__/__setattr__ hooks
 for computed attributes. While this approach is now a bit abandonned
 in favor of descriptors (properties or custom ones), it still works
 fine, and is probably the best solution to your problem.
 
 Ah, I didn't know about these - it looks as though they might be just
 the thing since it seems they're only called after all the other
 methods fail.

Right.

 That looks like there would be no performance hit, I
 wouldn't need to mess around with dynamically changing the class, and
 it would automatically deal with the (irritating) feature of having to
 check if there is already something in the object's dir() with that
 name. I'll look into this tomorrow - I hope this feature isn't going
 to be removed in future versions of Python?

I really don't think so. It's still has it's use for automatic 
delegation. And, as is the case here, for per-instance computed attributes.

As a side note: the naming symetry between __getattr__ and __setattr__ 
is a gotcha, since __setattr__ is mostly symetric to __getattribute__ - 
IOW, customizing __setattr__ is a bit tricky. The naive approach, ie:

class Parrot(object):
 def __setattr__(self, name, val):
 self.name = val

will indeed go into infinite recursion (or would, if the interpreter 
didn't stop it after a while)

The solution is of course to call on the parent class's __setattr__:

class Ni(object):
 def __setattr__(self, name, val):
 object.__setattr__(self, name, value)

HTH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Steven D'Aprano
On Thu, 07 Feb 2008 00:20:52 -0800, bearophileHUGS wrote:

 I think a high-level language like Python must have boolean operators
 (or and not) that behave in a much more clean way, with a simpler
 semantics. That is they have to return only true or false. Otherwise
 they are just a source of bugs and confusion.

Well, that's one opinion.

Boolean operators can be complicated to understand if you write 
complicated expressions, or if you don't understand what they do. But 
otherwise, they're no more complicated than arithmetic expressions.

[...]
 That trick with or/and may look good for Perl, but it's unfit for a
 language that tries to be clear, readable from people that don't know it
 much, and good to learn to program. Python has now the if-then
 expression too that is more clear.

Suppose I have two lists, and want to process the first one if it is not 
empty, otherwise process the second. I'd write it like this:

process(mylist or yourlist)

You're suggesting I should write it like this:

process(mylist if mylist else yourlist)


With the greatest respect, I think that if you think the second example 
is more clear, you're completely bonkers. *grins*


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Gary Duzan
In article [EMAIL PROTECTED],
Grant Edwards  [EMAIL PROTECTED] wrote:
On 2008-02-06, Reedick, Andrew [EMAIL PROTECTED] wrote:

 One demerit has been marked against your geek card for missing
 an obvious science pun.  Additionally, your membership to the
 Star Trek Lifestyle Adventure Club has been put on
 probationary status for the next twelve parsecs.

Ouch. Two demerits for using the distance unit parsec in a
context where a quantity of time was required.

   No demerits for Andrew; it is a Star Wars reference, which is
quite on topic for this subthread.

http://starwars.wikia.com/wiki/Kessel_Run

Gary Duzan
Motorola HNM


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Denis Bilenko
Tim Golden wrote:

 Dodging your question slightly (and at the risk of teaching
 my grandmother to suck eggs) I sometimes use this idiom for
 checking params. Obviously it only goes so far, but it's
 fairly compact:

 Noddy example code
 import os, sys

 if __name__ == '__main__':
   ARGS = None, DEV
   filename, db = \
 (j or i for i, j in map (None, ARGS, sys.argv[1:]))

   print sys.argv
   print filename, db

 /code

Thank you for the example. It demonstrates perfectly how
much people miss this feature :)


Raymond Hettinger wrote:

 At first blush that example would make it seem like a good idea, but I
 don't see how the example could extend past the first index.  If the
 port argument is optional, how would you know the index position of
 optional arguments to follow?

 With a dictionary, one could plausibly write:

  host = d.get('host', 'http://example.com')
  port = d.get('port', 8080)
  path = d.get('path', '/')

 But would this make sense with a list:

  host = s.get(0, 'http://example.com')
  port = d.get(1, 8080)
  path = d.get(2, '/')

 If positions 0 and 1 are optional, how do you expect to know whether
 path is going to be at position 2?  This problem doesn't exist with
 dictionaries because the presence or absence of optional entries does
 not affect the key reference to other entries.  Accordingly, I
 wouldn't expect that dict.get() would have a parallel list.get() with
 plausible use cases.

If you want to fill position 2, then positions 0 and 1 are mandatory.
It is the simplest possible option parsing, I didn't said it was the
most flexible :)

But perhaps it was a wrong example altogether.

Consider a couple more snippets, unrelated to command-line options.
(found by searching 'IndexError' in the python standard library)

this snippet from cmd.py:

try:
return self.completion_matches[state]
except IndexError:
return None

transforms into

return self.completion_matches.get(state)


another one from fileinput.py

try:
line = self._buffer[self._bufindex]
except IndexError:
pass
else:
self._bufindex += 1
self._lineno += 1
self._filelineno += 1
return line
line = self.readline()

becomes

line = self._buffer.get(self._bufindex)
if line:
self._bufindex += 1
self._lineno += 1
self._filelineno += 1
return line
line = self.readline()

both examples show reduction by 3 lines.

There's nothing dictionary-specific in 'get', it is
just a special use-case of '__getitem__' that is needed frequently.
Since list has '__getitem__' it deserves to have 'get' too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread bearophileHUGS
Steven D'Aprano:
 With the greatest respect, I think that if you think the second example
 is more clear, you're completely bonkers. *grins*

No one is completely normal, I presume :-)
I'd like to know what others think about it, about this anti-feature.
What I can say is that other computer languages too think that boolean
operations must return boolean values only, so I am not alone in my
folly :-)

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Stefan Behnel
Santiago Romero wrote:
  I'm impressed with python. I'm very happy with the language and I
 find Python+Pygame a very powerful and productive way of writing 2D
 games. I'm not, at this moment, worried about execution speed of the
 small game I'm working on (it runs at full 60 fps even in an old AMD-
 K6 450 Laptop computer), but I continue asking me the same question:
 
  Why not a Python COMPILER?
 
  It would be very nice to be able to output Linux, MAC or Windows
 binaries of compiled (not bytecompiled) code. It would run faster, it
 will be smaller in size (I think)

Take a look at Cython. It's an optimising Python-to-C compiler for writing
Python extensions. So you can basically take a Python module and compile it to
C code that runs against the CPython runtime.

http://cython.org/


 and it will be easy to distribute to
 people not having python installed. Yes, I know about py2exe, but I'm
 not sure if that's the right aproach.

That's a different focus, but then, there's portable Python.

http://www.portablepython.com/

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestions for structure of HTML-generating app

2008-02-07 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
 On Feb 5, 9:14 pm, Bernard [EMAIL PROTECTED] wrote:
 On 5 fév, 10:09, [EMAIL PROTECTED] [EMAIL PROTECTED]
 wrote:
 
 Are there any good approaches of doing this kind of thing that I've
 missed, or am I resigned to having HTML and Python code mixed and so
 will just have to keep all that nastiness to as few modules as
 possible?
 Thanks,
   Matthew.
 we use Cheetah templates to do just that at my workplace.
 we use CherryPy to generate the data and then we pass it on
 to the Cheetah template which handles the data and add html over it.
 here's an article on that matter 
 :http://www.onlamp.com/pub/a/python/2005/01/13/cheetah.html
 
 Thanks for the pointer to Cheetah.  At first glance it looks neat.
 Cherrytemplate has done well for me so far but I don't think it's
 under
 active development any more so it may be time to migrate.

You might also be interested in webstring:

http://psilib.sourceforge.net/webstring.html

(and then, there's tons of other templating packages for Python...)

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestions for structure of HTML-generating app

2008-02-07 Thread [EMAIL PROTECTED]
On Feb 5, 9:14 pm, Bernard [EMAIL PROTECTED] wrote:
 On 5 fév, 10:09, [EMAIL PROTECTED] [EMAIL PROTECTED]
 wrote:


  Are there any good approaches of doing this kind of thing that I've
  missed, or am I resigned to having HTML and Python code mixed and so
  will just have to keep all that nastiness to as few modules as
  possible?

  Thanks,
Matthew.

 we use Cheetah templates to do just that at my workplace.
 we use CherryPy to generate the data and then we pass it on
 to the Cheetah template which handles the data and add html over it.
 here's an article on that matter 
 :http://www.onlamp.com/pub/a/python/2005/01/13/cheetah.html

Thanks for the pointer to Cheetah.  At first glance it looks neat.
Cherrytemplate has done well for me so far but I don't think it's
under
active development any more so it may be time to migrate.

  Matthew.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: smtpd module

2008-02-07 Thread Stefan Witzel
Stefan Witzel wrote:

 Hello,
 
 the documentation of the smtpd module in the Python Library Reference
 is very short, I think. Are there any examples available? Especially
 I'm interested in the DebuggingServer.
 
 Thanks in advance.
 
 Stefan 

Sorry, I found the example - it's in the source file.

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Arnaud Delobelle
On Feb 7, 8:20 am, [EMAIL PROTECTED] wrote:
 Paul Rubin:

  I like the suggestion, except it should be
       port = int(sys.argv.get(1, '8000'))
  one could imagine your example going wrong in a protocol where 0 is
  a valid port number.

 I think a high-level language like Python must have boolean operators
 (or and not) that behave in a much more clean way, with a simpler
 semantics. That is they have to return only true or false. Otherwise
 they are just a source of bugs and confusion. This is a change fit for
 Python 3.
 That trick with or/and may look good for Perl, but it's unfit for a
 language that tries to be clear, readable from people that don't know
 it much, and good to learn to program. Python has now the if-then
 expression too that is more clear.

 Bye,
 bearophile

Personally, between

* foo if foo else bar
* foo or bar

I prefer the second. Maybe it could be spelt

* foo else bar ?

Moreover between the following two:

* foores = foo()
  foobar = foores if foores else bar

* foobar = foo() or bar

I also prefer the second.  Maybe it could be spelt

* foo() else bar ?

I have not thought of parsing issues :)

--
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Stefan Behnel
Denis Bilenko wrote:
 Raymond Hettinger wrote:
 If positions 0 and 1 are optional, how do you expect to know whether
 path is going to be at position 2?  This problem doesn't exist with
 dictionaries because the presence or absence of optional entries does
 not affect the key reference to other entries.  Accordingly, I
 wouldn't expect that dict.get() would have a parallel list.get() with
 plausible use cases.
 
 If you want to fill position 2, then positions 0 and 1 are mandatory.
 It is the simplest possible option parsing, I didn't said it was the
 most flexible :)

d = dict(enumerate(args))
print d[0], d[1], d.get(2)

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Traversing python datatypes via http

2008-02-07 Thread Matthew_WARREN







Mark [EMAIL PROTECTED] wrote

  Is it possible to traverse say python lists via http://

 http is a network protocol.
 What does that have to do with traversing python lists?
 Can you clarify what you mean by that?

  say there is a list in the memory
  can we traverse the list using list/next list/prev list/first
  list/last

 Not with a standard list although its not hard to do by defining
 your own class wrappibng a list.

 You can however traverse a list using a standard for loop:

 for item in [1,2,3,4,5]:
 print item

 And you can use range() to generate a set of indices
 that will allow you to iterate by more unusual step sizes

As well as range(), slicing can do;

for item in [1,2,3,4,5,6,7,8,9,0][::2]:
  print item

1
3
5
7
9

for item in [1,2,3,4,5,6,7,8,9,0][::-2]:
  print item

0
8
6
4
2


Matt.

--


This message and any attachments (the message) is
intended solely for the addressees and is confidential. 
If you receive this message in error, please delete it and 
immediately notify the sender. Any use not in accord with 
its purpose, any dissemination or disclosure, either whole 
or partial, is prohibited except formal approval. The internet
can not guarantee the integrity of this message. 
BNP PARIBAS (and its subsidiaries) shall (will) not 
therefore be liable for the message if modified. 
Do not print this message unless it is necessary,
consider the environment.

-

Ce message et toutes les pieces jointes (ci-apres le 
message) sont etablis a l'intention exclusive de ses 
destinataires et sont confidentiels. Si vous recevez ce 
message par erreur, merci de le detruire et d'en avertir 
immediatement l'expediteur. Toute utilisation de ce 
message non conforme a sa destination, toute diffusion 
ou toute publication, totale ou partielle, est interdite, sauf 
autorisation expresse. L'internet ne permettant pas 
d'assurer l'integrite de ce message, BNP PARIBAS (et ses
filiales) decline(nt) toute responsabilite au titre de ce 
message, dans l'hypothese ou il aurait ete modifie.
N'imprimez ce message que si necessaire,
pensez a l'environnement.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyGILState_Ensure() produces a deadlock

2008-02-07 Thread Alexander Eisenhuth
Hello,

In my mixed C++ / Python Application there are situations where a 
PyGILState_STATE gil_state = PyGILState_Ensure() produces a deadlock.

The background is that a call fro python to cpp is directed to another 
subsystem 
that tries to access the GIL (through my C++ wrapper) from another thread.

Does Pyhon API offer services to ship around that? Other hints?

Thanks a lot
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding properties to an instance

2008-02-07 Thread dg . google . groups
 As a side note: the naming symetry between __getattr__ and __setattr__
 is a gotcha, since __setattr__ is mostly symetric to __getattribute__ -
 IOW, customizing __setattr__ is a bit tricky. The naive approach, ie:

Ah I see - so __setattr__ is called immediately whereas __getattr__ is
only called if the other methods fail. Does this mean that __setattr__
incurs the same performance penalty that overriding __getattribute__
would? Possibly I can live with this because I think that most of what
I'm doing is getting attributes, or modifying mutable ones, rather
than setting them.

--
Dan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Jean-Paul Calderone
On Thu, 07 Feb 2008 11:03:12 +0100, Stefan Behnel [EMAIL PROTECTED] wrote:
Santiago Romero wrote:
 [snip]

  Why not a Python COMPILER?

  It would be very nice to be able to output Linux, MAC or Windows
 binaries of compiled (not bytecompiled) code. It would run faster, it
 will be smaller in size (I think)

Take a look at Cython. It's an optimising Python-to-C compiler for writing
Python extensions. So you can basically take a Python module and compile it to
C code that runs against the CPython runtime.

http://cython.org/


It's a not-quite-Python-to-C compiler.  I don't think it is an optimizing
compiler either.  Can you provide a reference for this?

Jean-Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for library to estimate likeness of two strings

2008-02-07 Thread Matthew_WARREN







 On Wed, 06 Feb 2008 17:32:53 -0600, Robert Kern wrote:

  Jeff Schwab wrote:
 ...
  If the strings happen to be the same length, the Levenshtein distance
  is equivalent to the Hamming distance.

Is this really what the OP was asking for. If I understand it correctly,
Levenshtein distance works out the number of edits required to transform
the string to the target string. The smaller the more equivalent, but with
the OP's problem I would expect


table1  table2
brian   briam
erian


I think the OP would like to guess at 'briam' rather than 'erian', but
Levenstein would rate them equally good guesses?

I know this is pushing it more toward phonetic alaysis of the words or
something similar, and thats orders of magnitude more complex.

just in case,

http://www.linguistlist.org/sp/Software.html#97

might be a good place to start looking into it, along with the NLTK
libraries here

http://nltk.sourceforge.net/index.php/Documentation



Matt.


--


This message and any attachments (the message) is
intended solely for the addressees and is confidential. 
If you receive this message in error, please delete it and 
immediately notify the sender. Any use not in accord with 
its purpose, any dissemination or disclosure, either whole 
or partial, is prohibited except formal approval. The internet
can not guarantee the integrity of this message. 
BNP PARIBAS (and its subsidiaries) shall (will) not 
therefore be liable for the message if modified. 
Do not print this message unless it is necessary,
consider the environment.

-

Ce message et toutes les pieces jointes (ci-apres le 
message) sont etablis a l'intention exclusive de ses 
destinataires et sont confidentiels. Si vous recevez ce 
message par erreur, merci de le detruire et d'en avertir 
immediatement l'expediteur. Toute utilisation de ce 
message non conforme a sa destination, toute diffusion 
ou toute publication, totale ou partielle, est interdite, sauf 
autorisation expresse. L'internet ne permettant pas 
d'assurer l'integrite de ce message, BNP PARIBAS (et ses
filiales) decline(nt) toute responsabilite au titre de ce 
message, dans l'hypothese ou il aurait ete modifie.
N'imprimez ce message que si necessaire,
pensez a l'environnement.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding properties to an instance

2008-02-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 As a side note: the naming symetry between __getattr__ and __setattr__
 is a gotcha, since __setattr__ is mostly symetric to __getattribute__ -
 IOW, customizing __setattr__ is a bit tricky. The naive approach, ie:
 
 Ah I see - so __setattr__ is called immediately whereas __getattr__ is
 only called if the other methods fail. 

Yes.

 Does this mean that __setattr__
 incurs the same performance penalty that overriding __getattribute__
 would? 

Not quite AFAICT - there's less going on here. Also, getting an 
attribute is (usually at least) more common than setting it.

 Possibly I can live with this because I think that most of what
 I'm doing is getting attributes, or modifying mutable ones, rather
 than setting them.

Well... Using the __setattr__/__getattr__ hooks is IMHO the simplest 
solution that can possibly work - far simpler than your previous one at 
least. As far as I'm concerned, and unless some other point of your 
specs make this unusable or unpractical, I'd go for this solution first 
and run a couple benchs on real-life-or-close-to conditions to check if 
the performance hit is acceptable.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Must COMMIT after SELECT (was: Very weird behavior in MySQLdb execute)

2008-02-07 Thread Paul Boddie
On 7 Feb, 08:52, Frank Aune [EMAIL PROTECTED] wrote:
 On Wednesday 06 February 2008 16:16:45 Paul Boddie wrote:

  Really, the rule is this: always (where the circumstances described
  above apply) make sure that you terminate a transaction before
  attempting to read committed, updated data.

 How exactly do you terminate a transaction then?Do you terminate a transaction
 by closing the cursor?

No, the transaction is controlled using the connection object in the
DB-API, specifically by the commit and rollback methods.

 Would this indicate that for each query you perform
 against the db, you should:

 - Open cursor
 - Perform query
 - Close cursor

I tend to open a separate cursor for each query whose result set I
want to keep around. In other words, if I'm doing a number of queries
whose results will not be manipulated via the DB-API (using fetchone,
fetchmany, fetchall) after the next query is executed, then I only
open one cursor - it's like this:

  cr = c.cursor()
  try:
cr.execute(query1)
do stuff with cr.fetchone/many/all
cr.execute(query2)
...
  finally:
cr.close()

As the DB-API indicates, if you want to manipulate more than one
result set, you need more than one cursor.

With PostgreSQL, my impression is that the intended way of using
cursors is not entirely compatible with the DB-API: you declare
cursors only when you know what the query will be, not in advance, and
they can only be used with certain kinds of operations. As far as I
recall, pyPgSQL supports cursors fairly transparently, albeit through
various ad-hoc measures, whereas psycopg2 only does so for named
cursors - a concept missing from the DB-API as far as I can see.

 The concept of cursor in MySQL is apparantly very different from what I
 originally thought. I always thought the cursor is the handler for a
 certain connection, and that you needed to commit before closing down this
 handler - else changes were automatically rolled back.

It's easy to believe this, given the hierarchical nature of the API.
However, cursors are just things which keep track of result sets, and
I suppose that they are most useful when you perform a query which
produces a large number of result rows, but where you only want to
read a limited number of those rows at a time.

Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding properties to an instance

2008-02-07 Thread dg . google . groups
  Does this mean that __setattr__
  incurs the same performance penalty that overriding __getattribute__
  would?

 Not quite AFAICT - there's less going on here. Also, getting an
 attribute is (usually at least) more common than setting it.

  Possibly I can live with this because I think that most of what
  I'm doing is getting attributes, or modifying mutable ones, rather
  than setting them.

 Well... Using the __setattr__/__getattr__ hooks is IMHO the simplest
 solution that can possibly work - far simpler than your previous one at
 least. As far as I'm concerned, and unless some other point of your
 specs make this unusable or unpractical, I'd go for this solution first
 and run a couple benchs on real-life-or-close-to conditions to check if
 the performance hit is acceptable.

I think you're right - I've just tried implementing a simple version
of this in my code and it seems that in the time critical parts of it
__setattr__ isn't called even once. So I think I'll go with this
solution (after having run a few tests).

Thanks for your suggestion!

--
Dan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Server side cookie problems

2008-02-07 Thread rodmc
On Feb 6, 8:00 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Wed, 06 Feb 2008 15:27:53 -0200, rodmc [EMAIL PROTECTED]
 escribi�:

  Hi, I am trying to set a cookie on a client computer using the Cookie
  module however all I get is the text being printed in the browser
  window. Can anyone point me in the right direction so that the cookie

  def writetocookie(number):
  #writes the ID of the database entry to a cookie
  cookie[dataid]=number
  print Content-Type: text/html
  print
  print Set-Cookie: dataid=,cookie[dataid].value

  I presume this is not the correct way to write a cookie, the examples
  I have found online don't seem to provide much more information.

 I don't know either if this is the right way, but surely the Set-Cookie
 header must appear *before* the blank line; that blank line separates the
 headers from the response body.

 --
 Gabriel Genellina

Thanks, that seemed to work.

rod
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Using a class as a structure/container

2008-02-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(snip)
 Thanks for the information.  The reason why I was taking this approach
 was more from a user interface perspective.  What I have is a file
 that contains certain geometric objects, lets call them geo.  Each geo
 object has 4 possible surfaces:

You mean it has one of the 4 surfaces, or it has them all ?

 ps, ss, le, te.  Each surface has
 x,y,z coordinates.  It is not known apriori if any of these surfaces
 exist in the file.  So I created a geo_reader class that is passed a
 filename in its argument list.  It then parses the file, creating a
 container class for each geo object and assigning the name geo0, geo1,
 geo2, etc... as an attribute of the geo_reader class.

You want an indexed ordered collection (ie: something like a list) here.

  The geo_reader
 class also stores global attributes concerning the file, i.e. the
 number of geo objects,

a list handle this.

 etc...  Then for each geo container I bind
 another container class for each surface that I find for each geo
 object, i.e. the ps, ss, le, te surfaces.  Then the coordinates for
 each of the surfaces becomes an attribute of each of their
 corresponding containers. 

Err... Why don't you actually take time to write the Geo and Surface 
classes ? It will *really* save you time in the long run.

 I can also bind certain attributes to the container class to tell
 whether its a geo object or surface, etc.

You definitively want to write the appropriate classes.

  I just didn't want the user
 to have to use the dictionary syntax like this:
 
 x_coords = my_geo['geo0']['ps']['x']

As far as I'm concerned, I'd use a list-like interface for my_geo, ie:

   my_geo[0].ps.x

And I'd define the four surface attributes of the Geo object, default 
them to either None or a NullSurface object (whose x and y attribs have 
the None value).

 It just seems a little more natural to use the dot operator approach
 for users to interface with.

wrt/ attribute access, yes, indeed. wrt/ what is clearly an ordered 
collection, there's already a well defined interface !-)

And anyway, this doesn't mean you should not properly define your 
classes - this is no more complex than what you're doing here, and it 
will make your code *way* more readable, maintainable and usable - even 
for your users, since they'll be able to introspect your objects type, 
print the docstrings (if you write them of course), eventually use 
autocompletion (cf the rlcompleter module) etc.

  I wasn't aware of the Law of Demeter and
 I agree with all your concerns.  I'm just not sure which one a user
 would rather interface with from the command line.  The dot operators
 are quicker to type.

Indeed. Now if you have such concern, why not go all the way ?-)

My 2 cents
-- 
http://mail.python.org/mailman/listinfo/python-list

index() of sequence type?

2008-02-07 Thread Neal Becker
I see list has index member, but is there an index function that applies to
any sequence type?

If not, shouldn't there be?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Server side cookie problems

2008-02-07 Thread rodmc
On Feb 7, 1:06 pm, rodmc [EMAIL PROTECTED] wrote:
 On Feb 6, 8:00 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:



  En Wed, 06 Feb 2008 15:27:53 -0200, rodmc [EMAIL PROTECTED]
  escribi�:

   Hi, I am trying to set a cookie on a client computer using the Cookie
   module however all I get is the text being printed in the browser
   window. Can anyone point me in the right direction so that the cookie

   def writetocookie(number):
   #writes the ID of the database entry to a cookie
   cookie[dataid]=number
   print Content-Type: text/html
   print
   print Set-Cookie: dataid=,cookie[dataid].value

   I presume this is not the correct way to write a cookie, the examples
   I have found online don't seem to provide much more information.

  I don't know either if this is the right way, but surely the Set-Cookie
  header must appear *before* the blank line; that blank line separates the
  headers from the response body.

  --
  Gabriel Genellina

 Thanks, that seemed to work.

 rod

Also how do I find out if a cookie has expired? I have tried various
methods but to no avail?

Cheers,

rod
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why does list have no 'get' method?

2008-02-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 Steven D'Aprano:
 With the greatest respect, I think that if you think the second example
 is more clear, you're completely bonkers. *grins*
 
 No one is completely normal, I presume :-)
 I'd like to know what others think about it, about this anti-feature.

s/anti//

 What I can say is that other computer languages too think that boolean
 operations must return boolean values only,

Not quite. In C and a couple other langages, int 0 is false, anything 
else is true. In Lisp (and IIRC), an empty list is false, anything else 
is true. I'm sure someone else could come with more than a couple other 
non-cryptic langages that just don't have a proper boolean type.

Using emptyness as a false value in boolean expressions is not that 
uncommon, and it has proven so far to be a working solution. Also, 
returning the tested object instead of a bool just makes sens to me. 
FWIW, booleans are a late addition to Python, and quite a couple persons 
where worried that it would only lead to confusion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Need Smart Phone with new features? please click here

2008-02-07 Thread Farooq
www.enmac.com.hk
GSM Mobile Phones, Digital iPods, Digital Clocks, Digital Pens,
Digital Quran. Enjoy these products with Islamic Features (Complete
Holy Quran with Text and Audio, Tafaseer books, Ahadees Books, Daily
Supplications, Universal Qibla Direction, Prayer Timing and much more)
visit our website for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginners help

2008-02-07 Thread Guilherme Polo
2008/2/7, Guido van Brakel [EMAIL PROTECTED]:
 Hello

  I totally new to python and i'm doing a python course now. Maybe someone
  could help me a little bit here:

  I need to create this script.

  If i enter a center digit like 5 for example i need to create two
  vertical and horzitonal rows that looks like this. If i enter 6 it shows
  6 six starts. How can i do this, because i don't have any clue.

  *
  *   *
  *   *
  *   *
  *


This would totally ruin the purpose of your course. Did you try
anything at all ?

  Kind Regards,

  --
  Guido van Brakel
  --

 --
  http://mail.python.org/mailman/listinfo/python-list



-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: index() of sequence type?

2008-02-07 Thread Stefan Behnel
Neal Becker wrote:
 I see list has index member, but is there an index function that applies to
 any sequence type?

Like this?

  def find_index(seq, value):
  try:
  find_index = seq.index
  except AttributeError:
  def find_index(value):
  for i,v in enumerate(seq):
   if v == value: return i
  raise ValueError(index(seq, x): x not in sequence)
  return find_index(value)


 If not, shouldn't there be?

I don't see the need.

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for library to estimate likeness of two strings

2008-02-07 Thread Lee Capps
At 14:01 Wed 06 Feb 2008, [EMAIL PROTECTED] wrote:
Are there any Python libraries implementing measurement of similarity
of two strings of Latin characters?

I'm writing a script to guess-merge two tables based on people's
names, which are not necessarily spelled the same way in both tables
(especially the given names).  I would like some function that would
help me make the best guess.

Many thanks in advance!

I used difflib.get_close_matches for something similar:

http://docs.python.org/lib/module-difflib.html

HTH.

-- 
Lee Capps
Technology Specialist
CTE Resource Center


-- 
http://mail.python.org/mailman/listinfo/python-list


beginners help

2008-02-07 Thread Guido van Brakel
Hello

I totally new to python and i'm doing a python course now. Maybe someone 
could help me a little bit here:

I need to create this script.

If i enter a center digit like 5 for example i need to create two 
vertical and horzitonal rows that looks like this. If i enter 6 it shows 
6 six starts. How can i do this, because i don't have any clue.

*
*   *
*   *
*   *
*

Kind Regards,

-- 
Guido van Brakel
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Ryszard Szopa
On Feb 5, 9:30 am, [EMAIL PROTECTED] wrote:

 I don't know the exact details but I think the issue is the dynamic
 nature of Python makes it impossible to correctly store the various
 types and changes into compiled code. Someone else will probably be
 able to provide a good reason as to why it isn't very feasible, nor a
 good idea. If you want to speed up your python look at Psyco. 
 http://psyco.sourceforge.net/

Yeah, but exactly what features make it so hard to write a compiler
for Python?

Common Lisp seems like a language at least as dynamic as Python, e.g.
you can change the type of objects at runtime, you can make changes to
functions, you can change classes at runtime, you can add methods and
generic functions (nb. these changes are reflected in existing
objects), you have a metaobject protocol. Moreover, you have
multimethods (in Python you don't, so it is one less thing to care).
However, Common Lisp has a few decent compilers (at least two open
source and two commercial).

Google tells me that such arguments have been raised back in 2001 [1].
I can add from myself that today Python is much more similar to Common
Lisp than in 2001. For example, multiple inheritance in Python = 2.3
behaves like in Dylan, which in turn behaves like CLOS with a twist.

What is more, apparently there is a Python compiler via CL: CLPython
(I don't have access to ACL, however, so I can't verify the claims of
the authors).

Finally, speaking of JIT compilers: recently has appeared something
that looks like  avery nice JIT compiler for Scheme, Ikarus [3].
Scheme is also quite dynamical, but is not OO, so I don't know how
viable is the analogy.

Of course, when writing Python extensions in C is fairly easy and when
rewriting just the critical part of the code is enough to get
acceptable performance, I really doubt I will see anybody willing to
invest serious amounts of money and time into writing a native
compiler for Python. Learning C cannot be so hard ;-). Also, this
seems consistent with Python viewed as a glue between libraries
written in C.


Cheers,

-- Richard

BIG FAT DISCLAIMER: I DO NOT want to start a Python vs. Common Lisp
and Scheme flame war.

[1] http://mail.python.org/pipermail/python-list/2001-April/080394.html
[2] http://common-lisp.net/project/clpython/
[3] http://www.cs.indiana.edu/~aghuloum/ikarus/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginners help

2008-02-07 Thread Diez B. Roggisch
Guido van Brakel wrote:

 Hello
 
 I totally new to python and i'm doing a python course now. Maybe someone
 could help me a little bit here:
 
 I need to create this script.
 
 If i enter a center digit like 5 for example i need to create two
 vertical and horzitonal rows that looks like this. If i enter 6 it shows
 6 six starts. How can i do this, because i don't have any clue.
 
 *
 *   *
 *   *
 *   *
 *

This list is not there to provide you with solutions to your homework. If
you try and show us your efforts, or have otherwise concrete questions you
certainly will get the help you want.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Must COMMIT after SELECT

2008-02-07 Thread Steve Holden
Paul Boddie wrote:
 On 7 Feb, 08:52, Frank Aune [EMAIL PROTECTED] wrote:
 On Wednesday 06 February 2008 16:16:45 Paul Boddie wrote:

 Really, the rule is this: always (where the circumstances described
 above apply) make sure that you terminate a transaction before
 attempting to read committed, updated data.
 How exactly do you terminate a transaction then?Do you terminate a 
 transaction
 by closing the cursor?
 
 No, the transaction is controlled using the connection object in the
 DB-API, specifically by the commit and rollback methods.
 
 Would this indicate that for each query you perform
 against the db, you should:

 - Open cursor
 - Perform query
 - Close cursor
 
 I tend to open a separate cursor for each query whose result set I
 want to keep around. In other words, if I'm doing a number of queries
 whose results will not be manipulated via the DB-API (using fetchone,
 fetchmany, fetchall) after the next query is executed, then I only
 open one cursor - it's like this:
 
   cr = c.cursor()
   try:
 cr.execute(query1)
 do stuff with cr.fetchone/many/all
 cr.execute(query2)
 ...
   finally:
 cr.close()
 
 As the DB-API indicates, if you want to manipulate more than one
 result set, you need more than one cursor.
 
Clearly you need multiple cursors if you want to be reading from the 
database on both cursors simultaneously. Like you, though, I tend to use 
a single cursor whenever I can get away with it (and now I think about 
it, that's probably because of the greater likelihood of seeing db 
consistency due to the read repeatability, though I can honestly say I 
hadn't really formalized that principle).

 With PostgreSQL, my impression is that the intended way of using
 cursors is not entirely compatible with the DB-API: you declare
 cursors only when you know what the query will be, not in advance, and
 they can only be used with certain kinds of operations. As far as I
 recall, pyPgSQL supports cursors fairly transparently, albeit through
 various ad-hoc measures, whereas psycopg2 only does so for named
 cursors - a concept missing from the DB-API as far as I can see.
 
Yes, unfortunately the nomenclature of the DB API conflicts with that of 
SQL'S DECLARE CURSOR, where the named cursor is effectively a sequence 
of query results that (under certain isolation levels and patterns of 
usage) can reflect database changes as they occur. Different 
implementers have chosen different relationships between DB API cursors 
and SQL cursors since it was introduced in the SQL 92 standard.

I believe, without documentary justification, that named cursors were 
introduced into SQL to support stored procedures, and therefore weren't 
intended to be used for queries whose results were communicated outside 
the server.

MySQL (never the most reliable indication of standardized SQL), 
restricts them to use inside stored procedures and triggers. PostgreSQL 
makes them more generally available, and I suppose it is possible to use 
a DB API cursor to execute a FETCH statement to retrieve data from a SQL 
CURSOR though I have never tried to do it.

SQL Server provides two types of cursor, one for use in the standard 
manner and one that conforms more closely with the ODBC cursor concept.

I tend to treat the database as a purely relational store, and not use 
stored procedures, but this is a luxury not everyone can afford - it's 
just necessary to use them for efficiency reasons sometimes, though not 
in the applications I am mostly involved with. Consequently I haven't 
made much use of SQL CURSORs.

 The concept of cursor in MySQL is apparantly very different from what I
 originally thought. I always thought the cursor is the handler for a
 certain connection, and that you needed to commit before closing down this
 handler - else changes were automatically rolled back.
 
 It's easy to believe this, given the hierarchical nature of the API.
 However, cursors are just things which keep track of result sets, and
 I suppose that they are most useful when you perform a query which
 produces a large number of result rows, but where you only want to
 read a limited number of those rows at a time.
 
That's true, and your remarks clarify cursor usage in the DB API very 
well. Most people most of the time tend to ignore the existence of 
cursor.fetchmany() in the DB API, despite the fact that it can provide 
huge efficiency gains over both .fetchone() (can slow processing by 
requiring too many database interactions per query) and .fetchmany() 
(which can generate large memory overhead in the case of huge result sets).

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: index() of sequence type?

2008-02-07 Thread Diez B. Roggisch
Neal Becker wrote:

 I see list has index member, but is there an index function that applies
 to any sequence type?
 
 If not, shouldn't there be?

Looks like an oversight to me as well, yes. The only difficult
implementation would be the one for xrange, because you can't search but
must compute the result - but that should be trivial. 

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Thomas Bellman
Bruno Desthuilliers [EMAIL PROTECTED] wrote:

 Not quite. In C and a couple other langages, int 0 is false, anything 
 else is true.

Not just int, but all kinds of integers, as well as all kinds of
floating point types and all kinds of pointers, with the value 0
are considered false.  And structs and unions can't be used in a
boolean context at all, and are thus neither true nor false.

   In Lisp (and IIRC), an empty list is false, anything else 
 is true.

There seems to be a language name missing from the parenthesis.
Were you perhaps thinking of Scheme?  If so, then no, in Scheme
only #f is false, and the empty list () is considered true.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
When C++ is your hammer, everything !  bellman @ lysator.liu.se
 looks like a thumb.!  Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Looking for library to estimate likeness of two strings

2008-02-07 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 
 
 
 
 
 
 On Wed, 06 Feb 2008 17:32:53 -0600, Robert Kern wrote:

 Jeff Schwab wrote:
 ...
 If the strings happen to be the same length, the Levenshtein distance
 is equivalent to the Hamming distance.
 
 Is this really what the OP was asking for. If I understand it correctly,
 Levenshtein distance works out the number of edits required to transform
 the string to the target string. The smaller the more equivalent, but with
 the OP's problem I would expect
 
 
 table1  table2
 brian   briam
 erian
 
 
 I think the OP would like to guess at 'briam' rather than 'erian', but
 Levenstein would rate them equally good guesses?
 
 I know this is pushing it more toward phonetic alaysis of the words or
 something similar, and thats orders of magnitude more complex.
 
 just in case,
 
 http://www.linguistlist.org/sp/Software.html#97
 
 might be a good place to start looking into it, along with the NLTK
 libraries here
 
 http://nltk.sourceforge.net/index.php/Documentation
 
You could perhaps use soundex to try to choose between different 
possibilities with the same Levenshtein distance from the sample. 
Soundex by itself is horrible, but it might work as a prioritizer.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python beginner problem(?)

2008-02-07 Thread Alan Illeman
Steve Holden [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Steve Holden wrote:
  Alan Illeman wrote:
  Win2k Pro - installed python: ok
 
 [...]
  =
  C:\Python25\Lib\site-packages\pythonwin\pywin\mfc\object.py:
  23: DeprecationWarning: raising a string exception is deprecated
raise win32ui.error, The MFC object has died.
  pwd=secret;database=master;uid=sa;server=mpilgrim
  =
 
  DiveIntoPython example 2.1 result:
  server=mpilgrim;uid=sa;database=master;pwd=secret
 
  ..which I realise is essentially the same (except for order).
 
  I haven't ever (not that I remember) installed MFC.
 
  Help!
 
 [...]
  I am hugely surprised to find that PythonWin apparently raises string
  exceptions: this is an old programming technique, which should have been
  removed from anything designed to run on Python 2.5. That is why you see
  the message: it's only a warning, so you can ignore it. I am copying
  Mark on this message in case he's unaware of the issue.
 [...]

 In a private reply Mark Hammond says he will fix this in the next
 release - thanks for the report!

 regards
   Steve
 -- 
 Steve Holden+1 571 484 6266   +1 800 494 3119
 Holden Web LLC  http://www.holdenweb.com/

Thanks Steve for both your replies.
Was (or is) python a piggyback for MFC?


-- 
http://mail.python.org/mailman/listinfo/python-list


print 'hello' - SyntaxError: invalid syntax

2008-02-07 Thread ValdezDE
I try to install Python in a Dell D620 with XP PRO  version 5.1.2600
and I am getting this error. I assume that some dlls are missing but I
installed form a fresh python-2.5.1.msi without errors msg.

Thanks

Roberto

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on
win32
Type help, copyright, credits or license for more information.
 import this
  File stdin, line 1
import this
   ^
SyntaxError: invalid syntax
 2 + 2
  File stdin, line 1
2 + 2
 ^
SyntaxError: invalid syntax
 print 'Hello'
  File stdin, line 1
print 'Hello'
 ^
SyntaxError: invalid syntax
 help
  File stdin, line 1
help
^
SyntaxError: invalid syntax

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Bruno Desthuilliers
Thomas Bellman a écrit :
 Bruno Desthuilliers [EMAIL PROTECTED] wrote:
 
(snip)
   In Lisp (and IIRC), an empty list is false, anything else 
 is true.
 
 There seems to be a language name missing from the parenthesis.

Yes, sorry - I was thinking of OCaml and/or Haskell, but couldn't 
remember which so I cout this out but forgot the (and IIRC).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Must COMMIT after SELECT

2008-02-07 Thread Paul Boddie
On 7 Feb, 14:29, Steve Holden [EMAIL PROTECTED] wrote:

 That's true, and your remarks clarify cursor usage in the DB API very
 well. Most people most of the time tend to ignore the existence of
 cursor.fetchmany() in the DB API, despite the fact that it can provide
 huge efficiency gains over both .fetchone() (can slow processing by
 requiring too many database interactions per query) and .fetchmany()

fetchall ;-)

 (which can generate large memory overhead in the case of huge result sets).

Indeed. I managed to run into a problem with DB-API-compliant code and
psycopg2 in this respect: select a large number of rows, watch
PostgreSQL do its work, see the Python process suck down the entire
result set. It's a situation reminiscent of that incident involving a
python and an alligator in the Florida swamps, but where the alligator
survives.

I don't use psycopg2 at the moment, but I did patch it to allow more
transparent usage of cursors, and there's an unapplied patch for this
floating around in the bug tracker. Lately, I've been using pyPgSQL
instead and not really doing huge selects from Python code anyway, but
I'm still using fetchmany for one or two things.

Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Bjoern Schliessmann
Ryszard Szopa wrote:

 Of course, when writing Python extensions in C is fairly easy and
 when rewriting just the critical part of the code is enough to get
 acceptable performance, I really doubt I will see anybody willing
 to invest serious amounts of money and time into writing a native
 compiler for Python. Learning C cannot be so hard ;-). 

Sure! Learning English also is not too hard. So everyone should be
capable of writing poetry of Shakespeare niveau.

Regards,


Björn

-- 
BOFH excuse #69:

knot in cables caused data stream to become twisted and kinked

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Steve Holden
Wildemar Wildenburger wrote:
 Arnaud Delobelle wrote:
 Personally, between

 * foo if foo else bar
 * foo or bar

 I prefer the second. Maybe it could be spelt

 * foo else bar ?

 How about
 
 val = foo rather than bar
 
 If that is not clear and obvios, I don't know what is.  ;)
 
Even clearer:

ASSIGN foo IF foo HAS A VALUE, OTHERWISE bar, TO val

Ahh, the joys of the COmmon Business Oriented Language.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Wildemar Wildenburger
Arnaud Delobelle wrote:
 Personally, between
 
 * foo if foo else bar
 * foo or bar
 
 I prefer the second. Maybe it could be spelt
 
 * foo else bar ?
 
How about

val = foo rather than bar

If that is not clear and obvios, I don't know what is.  ;)

/W
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket script from perl - python

2008-02-07 Thread Bjoern Schliessmann
kettle wrote:

 Hi I have a socket script, written in perl, which I use to send
 audio data from one server to another.  I would like to rewrite
 this in python so as to replicate exactly the functionality of the
 perl script, so as to incorporate this into a larger python
 program. Unfortunately I still don't really have the hang of
 socket programming in python.

Socket programming in Python is just like socket programming in C. I
suppose with Perl it's the same.

 # pack $length as a 32-bit network-independent long
 my $len = pack('N', $length);
 [...]
 I've used python's socket library to connect to the server, and
 verified that the first piece of data'r' is read correctly, the
 sticking point seems to be the $len variable.  I've tried using
 socket.htonl() and the other less likely variants, but nothing
 seem to produce the desired result, which would be to have the
 server-side message print the same 'length' as the length printed
 by the client.

Try struct.calcsize.
 
Regards,


Björn

-- 
BOFH excuse #88:

Boss' kid fucked up the machine

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Must COMMIT after SELECT

2008-02-07 Thread M.-A. Lemburg
On 2008-02-07 16:46, Carsten Haese wrote:
 On Thu, 2008-02-07 at 16:33 +0100, M.-A. Lemburg wrote:
 mxODBC has support for named cursors that you can later
 use for positioned updates. 
 
 Since we're on the topic of shameless plugs, InformixDB has this
 feature, too :)
 
 However, it's usually better to do updates in the classical
 way, ie. by referencing a primary key.
 
 That depends on the notion of better. It's entirely possible that a
 WHERE CURRENT OF cursor clause finds the row in question faster than
 even an indexed access using a primary key could. If you're processing a
 single row, I would agree that using an update cursor is overkill, but
 if you're processing a large number of rows, using an update cursor
 might be beneficial.

Agreed.

This approach is also very useful if you have to do extra analysis
of the rows in question *outside* the database, before selecting them
for update.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Feb 07 2008)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple interpreters retaining huge amounts of memory

2008-02-07 Thread Rhamphoryncus
On Feb 2, 10:32 pm, Graham Dumpleton [EMAIL PROTECTED]
wrote:
 The multi interpreter feature has some limitations, but if you know
 what you are doing and your application can be run within those
 limitations then it works fine.

I've been wondering about this for a while.  Given the severe
limitations of it, what are the use cases where multiple interpreters
do work?  All I can think of is that it keeps separate copies of
loaded python modules, but since you shouldn't be monkey-patching them
anyway, why should you care?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Michael Spencer
Wildemar Wildenburger wrote:
 Arnaud Delobelle wrote:
 Personally, between

 * foo if foo else bar
 * foo or bar

 I prefer the second. Maybe it could be spelt

 * foo else bar ?

 How about
 
 val = foo rather than bar
 
 If that is not clear and obvios, I don't know what is.  ;)
 
 /W
Excellent suggestion, and obviously its semantics should be:

   val = foo if bar else foo

and so, some might argue for:

   val = foo despite bar

which would allow more aggressive short-circuiting.  However, I'm not sure how 
useful this is in practice.

M




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedded python in c++ packaging

2008-02-07 Thread Joshua Kugler
Furkan Kuru wrote:
 Hello,
 
 I have been developing an application in C++ that embeds Python
 interpreter. It takes advantage of too many modules from Python.
 When I want to package this application, I need to add too many files
 (.pyc) from Python/lib folder together with Python25.dll.
 Is there a way to pack these .pyc files to a zip file and redirect
 Python25.dll to that zip file?

That is effectively what py2exe does with the modules required by the main
application.  It takes all the required modules and puts them in a
library.zip file.  You might take a look at how it does it.

j

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython vs CPython: faster in 1.6 times?

2008-02-07 Thread Isaac Gouy
On Feb 6, 1:54 pm, Stefan Behnel [EMAIL PROTECTED] wrote:
 Isaac Gouy wrote:
  On Feb 5, 11:47 am, Stefan Behnel [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] schrieb:

  Mike C. Fletcher:
  Not sure if Mono also provides a speedup.
  There is a set of good benchmarks here, the answer is negative:
 http://shootout.alioth.debian.org/sandbox/benchmark.php?test=all〈...
  This doesn't look like Mono to me:

  IronPython 1.1 (1.1) on .NET 2.0.50727.42

  Stefan

  Have you actually looked at the version string from IronPython-1.1-
  Bin.zip running on Mono?

 Why? Would that look like Mono? :)

 Stefan

Why? Because then you'd be doing more than expressing your personal
ignorance.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: embedded python in c++ packaging

2008-02-07 Thread Warren Myers
The Python byte-code files are already pretty dense, so compressing them
further is unlikely to work if you try to put them in a zip.

WMM

On Feb 7, 2008 11:39 AM, Furkan Kuru [EMAIL PROTECTED] wrote:

 Hello,

 I have been developing an application in C++ that embeds Python
 interpreter.
 It takes advantage of too many modules from Python.
 When I want to package this application, I need to add too many files
 (.pyc) from Python/lib folder together with Python25.dll.
 Is there a way to pack these .pyc files to a zip file and redirect
 Python25.dll to that zip file?

 Thanks in advance.

 --
 Furkan Kuru

 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
http://warrenmyers.com
God may not play dice with the universe, but something strange is going on
with the prime numbers. --Paul Erdős
It's not possible. We are the type of people who have everything in our
favor going against us. --Ben Jarhvi, Short Circuit 2
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: re question

2008-02-07 Thread Amit Gupta
On Feb 7, 10:38 am, Amit Gupta [EMAIL PROTECTED] wrote:
 Python'ites

 I searched around google to find the answer to this question, but I
 can't:

 I have a named regexp : x = re.compile((?Pme[a-z]+))

 What I want is an iterator, that can return me both the groupname
 and the matched string,  e.g:

 m = x.search(aa)

 Somehow, I want to get
 {me : aa}, either as dictionary or some iterable form.

 All I found is, I need to know the groupname to get the
 corresponding match. Any help is appreciated.

 A

Got It. re.search() has a function groupdict(), doing precisely that.
-- 
http://mail.python.org/mailman/listinfo/python-list


MyHDL project!!

2008-02-07 Thread Blubaugh, David A.
 sir,


Is there still a possibility to collaborate???  


David Blubaugh


-Original Message-
From: Blubaugh, David A. 
Sent: Friday, February 01, 2008 10:44 AM
To: 'chewie54'
Cc: 'python-list@python.org'
Subject: MyHDL project !

Dan,


I would be honored to start a project such as that in mind.  How do we
begin ??


David Blubaugh


 

-Original Message-
From: chewie54 [mailto:[EMAIL PROTECTED]
Sent: Thursday, January 31, 2008 9:34 PM
To: python-list@python.org
Subject: Re: Will Python on day
replaceMATLAB?

 I have been evaluating the python environment ever more closer.  I 
 believe I can interface python with a development environment known as

 the ImpulseC environment.  The ImpulseC environment develops C to VHDL
 for FPGA development. I would especially love to interface Python
 with ImpulseC and the graphing capabilities of GNU Plot and SciPy in 
 order to recreate a VHDL development environment that will be just as 
 capable as a $50,000 dollar Matlab to VHDL toolbox.  This is also a 
 part of my Masters thesis.  Is anyone willing to help in this
endeavor?

 David Blubaugh


Why not use MyHDL which is written in Python and translates to Verilog.
I assume ImpulseC is a commercial product and costs a log.  MyHDL is
free.
If you have any interests in combining MyHDL with SciPy and NumPy I
would be interested in getting involved.

Dan Fabrizio


This e-mail transmission contains information that is confidential and may be 
privileged.   It is intended only for the addressee(s) named above. If you 
receive this e-mail in error, please do not read, copy or disseminate it in any 
manner. If you are not the intended recipient, any disclosure, copying, 
distribution or use of the contents of this information is prohibited. Please 
reply to the message immediately by informing the sender that the message was 
misdirected. After replying, please erase it from your computer system. Your 
assistance in correcting this error is appreciated.


-- 
http://mail.python.org/mailman/listinfo/python-list


re question

2008-02-07 Thread Amit Gupta
Python'ites

I searched around google to find the answer to this question, but I
can't:

I have a named regexp : x = re.compile((?Pme[a-z]+))

What I want is an iterator, that can return me both the groupname
and the matched string,  e.g:

m = x.search(aa)

Somehow, I want to get
{me : aa}, either as dictionary or some iterable form.


All I found is, I need to know the groupname to get the
corresponding match. Any help is appreciated.

A
-- 
http://mail.python.org/mailman/listinfo/python-list


Setting up a new user and environment from within a python script

2008-02-07 Thread Henry Hollenberg
Hello,

I have written a script that uses environment variables set during
a particular users login in .bash_profile and .profile.

I have changed to that users uid and gid in my python script using:

import os
os.setegid
os.setgid
os.seteuid
os.setuid

but I still am not picking up the needed environment.  When I run:
os.environ I can see that I still have the environment of the user
that owns the python script.

I would like to maintain the original script owner but somehow pick up
the
correct environment for the targeted user.  Several options looked to
create
an environment in a sub-process which I don't think is the correct
solution.

I could of course cut and paste the values from .bash_profile 
.profile
but figured there is probably a better, cleaner way to do the same.

Searched this forum with no luck and checked several python
references.

What is the best practice to achieve this goal?

Thanks, Henry Hollenberg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread pruebauno
On Feb 7, 12:15 pm, [EMAIL PROTECTED] wrote:
 On Feb 7, 11:01 am, Denis Bilenko [EMAIL PROTECTED] wrote:



  Steve Holden wrote:
   These versions differ with respect to treatment of blank lines, which
   indicates  how easy it is to go astray in this kind of semantic
   optimization. Your example simply wouldn't work (though you could patch
   it up using if line is None. (despite the use of short-circuiting
   predicates).
both examples show reduction by 3 lines.

   Perhaps so, but you have to realise that Python has never valued code
   compactness over clarity.
   I'm not sure that your democratic wish to ensure fairness to sequences
   will garner much support, interesting though it is in an academic sense.

  Thank you for the patch. My incentives are not academic though.

  I convinced that this

  line = self._buffer.get(self._bufindex)
  if line is None:
  self._bufindex += 1
  self._lineno += 1
  self._filelineno += 1
  return line
  line = self.readline()

  is more clear than

  try:
  line = self._buffer[self._bufindex]
  except IndexError:
  pass
  else:
  self._bufindex += 1
  self._lineno += 1
  self._filelineno += 1
  return line
  line = self.readline()

  I mentioned 3 lines reduction just because it is
  objective, while 'more clear' is subjective.

  Code snippets are again not equivalent, e.g. in the
  case when self._buffer[self._bufindex] exists and is
  equal to None. Although the author could probably
  make a guarantee that is never the case.

 This has been a pet peeve of mine too. So you are not completely
 crazy:

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269484

 There is a discussion about precisely this by Alex Martelli in the
 printed version of the Python cookbook (2nd edition). I don't share
 the opinion but I am not going to fight the core Python developers
 over it. I don't think it is worth the effort. Python is so smooth
 already, there has to be some excuse to add some cute hack to your
 program once in a while :-).

 dict(enumerate(lst)).get(i,default) for example although not very
 efficient, looks cute. I think I like it better than my own solution.

Actually to clarify, I think this is more useful for tuples (or tuple
like structures) than lists per se. On homogeneous lists I usually
iterate. It is on heterogeneous that I want to extract specific fields
that might be optional.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to use .NET DLL from Python

2008-02-07 Thread Christian Heimes
Huayang Xia wrote:
 What's the difference between .NET DLL and normal C DLL? Do you mean
 after clr.AddReference('ClassLibrary1'), there is no need to import
 ClassLibrary1?

A normal DLL and an assembly DLL share only the header. The rest is
totally different. You can see the DLL as a container for the CIL code.

clr.AddReference('ClassLibrary1') makes the namespaces of the
ClassLibrary1 assembly available to IronPython and PythonDotNET. import
ClassLibrary1 imports the name space. You must import the assembly
before you can use its name spaces.

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket script from perl - python

2008-02-07 Thread Hrvoje Niksic
kettle [EMAIL PROTECTED] writes:

 # pack $length as a 32-bit network-independent long
 my $len = pack('N', $length);
[...]
 the sticking point seems to be the $len variable.

Use len = struct.pack('!L', length) in Python.  See
http://docs.python.org/lib/module-struct.html for details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting all user defined attributes of a class

2008-02-07 Thread Amit Gupta
On Feb 7, 12:28 am, grflanagan [EMAIL PROTECTED] wrote:
 On Feb 6, 11:07 pm, Amit Gupta [EMAIL PROTECTED] wrote:

  Hi

  How do I get user defined attributes of a class? e.g

  Class A(object) :
self.x = 1
  --

  I want something like:
for userattrib in A.getAllUserAttribute() :
  print userattrib
[..]

 HTH

 Gerard

Thanks. What I found is: If I call iterate over the __dict__ of the
instance of the class, I only get user-atttributes and not built-in
attributes. I have an instance of that class, anyway, so this will do.
However, I wonder if I am getting just lucky and this might change in
future. In that regard the solution provides by all posters above
might well be more robust.

A
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: brain stuck. whats occurring here?

2008-02-07 Thread [EMAIL PROTECTED]
On Feb 7, 11:38 am, [EMAIL PROTECTED] wrote:
 Hallo,

 I'm after

 [[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[]­,[],[],[]]]

 (NxN 'grid', 5x5 in that example, and while typing this up i figured out
 how to get it, but I'm still not sure what _was_ happening)

 I'm trying

  a=[]
  row=[ [] for n in range(0,10) ]
  a.extend(row[:])
  a

 [[], [], [], [], [], [], [], [], [], []] a[0].extend(row[:])
  a

 [[[...], [], [], [], [], [], [], [], [], []], [], [], [], [], [], [], [],
 [], []]

 why isnt that last a

 [[[...]],[],[],[],[],[],[],[],[],[]]

 Puzzled :)

I don't see why you should get either.

Especially considering this behaviour:

 a=[]
 row=[ [] for n in range(0,10) ]
 a.extend(row[:])
 a
[[], [], [], [], [], [], [], [], [], []]
 a[0].extend(row[:])
 a
[[[...], [], [], [], [], [], [], [], [], []], [], [], [], [], [], [],
[], [], []]

 a[0][0][0][0][0][0][0][0][0][0][0][0][0][0]
[[...], [], [], [], [], [], [], [], [], []]

 a=[]
 row=[ [] for n in range(0,10) ]
 a.extend(row[:])
 a
[[], [], [], [], [], [], [], [], [], []]

Bug in IDLE?


 Matt.
 --

 This message and any attachments (the message) is
 intended solely for the addressees and is confidential.
 If you receive this message in error, please delete it and
 immediately notify the sender. Any use not in accord with
 its purpose, any dissemination or disclosure, either whole
 or partial, is prohibited except formal approval. The internet
 can not guarantee the integrity of this message.
 BNP PARIBAS (and its subsidiaries) shall (will) not
 therefore be liable for the message if modified.
 Do not print this message unless it is necessary,
 consider the environment.

                 -

 Ce message et toutes les pieces jointes (ci-apres le
 message) sont etablis a l'intention exclusive de ses
 destinataires et sont confidentiels. Si vous recevez ce
 message par erreur, merci de le detruire et d'en avertir
 immediatement l'expediteur. Toute utilisation de ce
 message non conforme a sa destination, toute diffusion
 ou toute publication, totale ou partielle, est interdite, sauf
 autorisation expresse. L'internet ne permettant pas
 d'assurer l'integrite de ce message, BNP PARIBAS (et ses
 filiales) decline(nt) toute responsabilite au titre de ce
 message, dans l'hypothese ou il aurait ete modifie.
 N'imprimez ce message que si necessaire,
 pensez a l'environnement.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Grant Edwards
On 2008-02-06, Gary Duzan [EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED],
 Grant Edwards  [EMAIL PROTECTED] wrote:
On 2008-02-06, Reedick, Andrew [EMAIL PROTECTED] wrote:

 One demerit has been marked against your geek card for missing
 an obvious science pun.  Additionally, your membership to the
 Star Trek Lifestyle Adventure Club has been put on
 probationary status for the next twelve parsecs.

Ouch. Two demerits for using the distance unit parsec in a
context where a quantity of time was required.

No demerits for Andrew; it is a Star Wars reference, which is
 quite on topic for this subthread.

 http://starwars.wikia.com/wiki/Kessel_Run

Silly me.

I wonder if George Lucas intended it as a joke or if he thought
a parsec was a unit of time.

-- 
Grant Edwards   grante Yow! Clear the laundromat!!
  at   This whirl-o-matic just had
   visi.coma nuclear meltdown!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Torsten Bronger
Hallöchen!

Grant Edwards writes:

 On 2008-02-06, Gary Duzan [EMAIL PROTECTED] wrote:

 In article [EMAIL PROTECTED],

 Grant Edwards  [EMAIL PROTECTED] wrote:

 [...]

 Ouch. Two demerits for using the distance unit parsec in a
 context where a quantity of time was required.

 No demerits for Andrew; it is a Star Wars reference, which is
 quite on topic for this subthread.

 http://starwars.wikia.com/wiki/Kessel_Run

 Silly me.

 I wonder if George Lucas intended it as a joke or if he thought
 a parsec was a unit of time.

The latter because it was corrected in the novelization.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to use .NET DLL from Python

2008-02-07 Thread Fuzzyman
On Feb 7, 2:35 pm, Luis M. González [EMAIL PROTECTED] wrote:
 On 7 feb, 05:52, Fuzzyman [EMAIL PROTECTED] wrote:



  Luis M. González wrote:
   On 6 feb, 21:17, Fuzzyman [EMAIL PROTECTED] wrote:
On Feb 6, 9:59 pm, Luis M. Gonz�lez [EMAIL PROTECTED] wrote:

 On Feb 6, 6:27 pm, Huayang Xia [EMAIL PROTECTED] wrote:

  Hello All,

  I have several .NET DLL (I have no source code for them), is there
  anyway to use them from python instead of from C#.

  Thanks,
  Huayang

 I used to put my .dll files into the .DLL folder, so I could simply
 import them as I would with any other python module.
 But since I started using Ironpython 2.0 Alpha* this doesn't work
 anymore...
 Any hint?

The rule is probably still that the DLLs must be in a directory on
sys.path for the interpreter to find them. Try adding the directory
containing the assemblies to sys.path and see if you can add
references to them.

Michael Foordhttp://www.manning.com/foord

 Luis

   I tried adding the directory to sys.path.
   Still not working...

import sys
sys.path.append('C:\Documents and 
Settings\luismg\Escritorio\IronPython-2.0A
   8\DLLs')
from ClassLibrary1 import *
   Traceback (most recent call last):
 File , line unknown, in ##235
 File , line unknown, in _stub_##2
   ImportError: No module named ClassLibrary1

  You need to add references to assemblies before you can import from
  the namespaces they contain.

  import clr
  clr.AddReference('ClassLibrary1')

  HTH

  Fuzzymanhttp://www.manning.com/foord

 Oh, I know what you mean.
 But that was exactly the reason for having a .DLLs folder, isn't it?
 When you place an assembly into this folder, you avoid having to write
 this boilerplate code, and simply import the assembly as you would
 with a normal python module. At least, that´s how it worked in
 previous versions...

No. You have always had to add references to assemblies before being
able to use the namespaces they contain. You even have to do this with
C# in Visual Studio.

Michael
http://www.manning.com/foord
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Looking for library to estimate likeness of two strings

2008-02-07 Thread Gabriel Genellina
En Thu, 07 Feb 2008 13:25:14 -0200, [EMAIL PROTECTED] [EMAIL PROTECTED]  
escribió:

 Many thanks for the excellent leads.  I've also found several
 functions to find phonetic similarity between English names: the
 mentioned above soundex, then, also, one called metaphone.  I'm now
 thinking of the best way to use some combination of these functions.

You may be interested in this article which discusses some techniques used  
to match similar records:

Record Linkage: A Machine Learning Approach, A Toolbox, and A Digital
Government Web Service (2003)
Mohamed G. Elfeky, Vassilios S. Verykios, Ahmed K. Elmagarmid, Thanaa
M. Ghanem, Ahmed R. Huwait.
http://citeseer.ist.psu.edu/elfeky03record.html


-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to use .NET DLL from Python

2008-02-07 Thread Huayang Xia
What's the difference between .NET DLL and normal C DLL? Do you mean
after clr.AddReference('ClassLibrary1'), there is no need to import
ClassLibrary1?
-- 
http://mail.python.org/mailman/listinfo/python-list


brain stuck. whats occurring here?

2008-02-07 Thread Matthew_WARREN
Hallo,

I'm after

[[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]]]

(NxN 'grid', 5x5 in that example, and while typing this up i figured out
how to get it, but I'm still not sure what _was_ happening)


I'm trying

 a=[]
 row=[ [] for n in range(0,10) ]
 a.extend(row[:])
 a
[[], [], [], [], [], [], [], [], [], []]
 a[0].extend(row[:])
 a
[[[...], [], [], [], [], [], [], [], [], []], [], [], [], [], [], [], [],
[], []]


why isnt that last a

[[[...]],[],[],[],[],[],[],[],[],[]]


Puzzled :)

Matt.
--


This message and any attachments (the message) is
intended solely for the addressees and is confidential. 
If you receive this message in error, please delete it and 
immediately notify the sender. Any use not in accord with 
its purpose, any dissemination or disclosure, either whole 
or partial, is prohibited except formal approval. The internet
can not guarantee the integrity of this message. 
BNP PARIBAS (and its subsidiaries) shall (will) not 
therefore be liable for the message if modified. 
Do not print this message unless it is necessary,
consider the environment.

-

Ce message et toutes les pieces jointes (ci-apres le 
message) sont etablis a l'intention exclusive de ses 
destinataires et sont confidentiels. Si vous recevez ce 
message par erreur, merci de le detruire et d'en avertir 
immediatement l'expediteur. Toute utilisation de ce 
message non conforme a sa destination, toute diffusion 
ou toute publication, totale ou partielle, est interdite, sauf 
autorisation expresse. L'internet ne permettant pas 
d'assurer l'integrite de ce message, BNP PARIBAS (et ses
filiales) decline(nt) toute responsabilite au titre de ce 
message, dans l'hypothese ou il aurait ete modifie.
N'imprimez ce message que si necessaire,
pensez a l'environnement.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a trick with lists ?

2008-02-07 Thread Diez B. Roggisch
S�� schrieb:
 I've found some class on the Net which takes basically this form :
 
 ##
 class Foo:
 def __init__(self):
 self.tasks = []
...
 
 def method1(self):
 tasks = []
 while True:
   ...
   append/pop elements into/from tasks
   ...
   if condition : break
 
 self.tasks[:] = tasks
 return
 ##
 
 What I do not fully understand is the line self.tasks[:] = tasks. Why does 
 the guy who coded this did not write it as self.tasks = tasks? What is the 
 use of the [:] trick ?

It changes the list in-place. If it has been given to other objects, it 
might require that.


Diez
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why does list have no 'get' method?

2008-02-07 Thread pruebauno
On Feb 7, 11:01 am, Denis Bilenko [EMAIL PROTECTED] wrote:
 Steve Holden wrote:
  These versions differ with respect to treatment of blank lines, which
  indicates  how easy it is to go astray in this kind of semantic
  optimization. Your example simply wouldn't work (though you could patch
  it up using if line is None. (despite the use of short-circuiting
  predicates).
   both examples show reduction by 3 lines.

  Perhaps so, but you have to realise that Python has never valued code
  compactness over clarity.
  I'm not sure that your democratic wish to ensure fairness to sequences
  will garner much support, interesting though it is in an academic sense.

 Thank you for the patch. My incentives are not academic though.

 I convinced that this

 line = self._buffer.get(self._bufindex)
 if line is None:
 self._bufindex += 1
 self._lineno += 1
 self._filelineno += 1
 return line
 line = self.readline()

 is more clear than

 try:
 line = self._buffer[self._bufindex]
 except IndexError:
 pass
 else:
 self._bufindex += 1
 self._lineno += 1
 self._filelineno += 1
 return line
 line = self.readline()

 I mentioned 3 lines reduction just because it is
 objective, while 'more clear' is subjective.

 Code snippets are again not equivalent, e.g. in the
 case when self._buffer[self._bufindex] exists and is
 equal to None. Although the author could probably
 make a guarantee that is never the case.

This has been a pet peeve of mine too. So you are not completely
crazy:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269484

There is a discussion about precisely this by Alex Martelli in the
printed version of the Python cookbook (2nd edition). I don't share
the opinion but I am not going to fight the core Python developers
over it. I don't think it is worth the effort. Python is so smooth
already, there has to be some excuse to add some cute hack to your
program once in a while :-).

dict(enumerate(lst)).get(i,default) for example although not very
efficient, looks cute. I think I like it better than my own solution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python beginner problem(?)

2008-02-07 Thread Alan Illeman
Steve Holden [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Alan Illeman wrote:
 
  Thanks Steve for both your replies.
  Was (or is) python a piggyback for MFC?
 
 
 You are supposed to be able to access the MFC classes through PythonWin,
 but I have never personally bothered because MFC is too horrible to
 tangle with.

 regards
   Steve

That's a relief; I always hated MFC. Thanks.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distinguishing between functions and methods in a decorator.

2008-02-07 Thread Diez B. Roggisch
Berteun Damman wrote:

 Hello,
 
 I was wondering a bit about the differences between methods and
 functions. I have the following:
 
 def wrap(arg):
 print type(arg)
 return arg
 
 class C:
 def f():
 pass
 
 @wrap
 def g():
 pass
 
 def h():
 pass
 
 print type(C.f)
 print type(h)
 
 Which gives the following output:
 type 'function'
 type 'instancemethod'
 type 'function'
 
 The first line is caused by the 'wrap' function of course. I had
 expected the first line to be 'instancemethod' too. So, I would guess,
 these methods of C are first created as functions, and only then become
 methods after they are 'attached' to some classobj. (You can do that
 yourself of course, by saying, for example, C.h = h, then the type of
 C.h is 'instancemethod' too.)
 
 Why does the wrapping occur before the function is 'made' into an
 instancemethod?

Because a decorator could choose to return any function-object as it likes,
see this example:

def bar(self):
print bar

def makebar(f):
return bar

class Foo(object):

   @makebar
   def baz(self):
   pass

foo = Foo()
foo.baz()

So you can't decide if a function is an instancemethod until the very last
moment. 

Diez   
-- 
http://mail.python.org/mailman/listinfo/python-list


Distinguishing between functions and methods in a decorator.

2008-02-07 Thread Berteun Damman
Hello,

I was wondering a bit about the differences between methods and
functions. I have the following:

def wrap(arg):
print type(arg)
return arg

class C:
def f():
pass

@wrap
def g():
pass

def h():
pass

print type(C.f)
print type(h)

Which gives the following output:
type 'function'
type 'instancemethod'
type 'function'

The first line is caused by the 'wrap' function of course. I had
expected the first line to be 'instancemethod' too. So, I would guess,
these methods of C are first created as functions, and only then become
methods after they are 'attached' to some classobj. (You can do that
yourself of course, by saying, for example, C.h = h, then the type of
C.h is 'instancemethod' too.)

Why does the wrapping occur before the function is 'made' into an
instancemethod?

The reason for asking is that I would like to differentiate between
wrapping a function and an instancemethod, because in the latter case,
the first parameter will be the implicit 'self', which I would like to
ignore.  However, when the wrapping occurs, the method still looks like
a function.

Berteun
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Stefan Behnel
Jean-Paul Calderone wrote:
 On Thu, 07 Feb 2008 11:03:12 +0100, Stefan Behnel [EMAIL PROTECTED]
 wrote:
 Take a look at Cython. It's an optimising Python-to-C compiler for
 writing
 Python extensions. So you can basically take a Python module and
 compile it to
 C code that runs against the CPython runtime.

 http://cython.org/
 
 It's a not-quite-Python-to-C compiler.

Ok, there are differences. For example, you can't define functions dynamically
(it doesn't currently support closures anyway). But it already supports a much
wider subset of the language than Pyrex originally did. For example, you can
use list comprehensions and Python 3 keyword-only arguments in function
signatures. I would expect it would compile quite a lot of Python code out
there without or with only minor modifications.


 I don't think it is an optimizing
 compiler either.  Can you provide a reference for this?

It optimises a lot of common patterns into very fast sequences of Python API
calls (or even generates specialised non-API code for them). It also generates
optimised runtime code for special cases based on the type of an object (e.g.
if the object you iterate turns out to be a list, it uses fast list API calls
in loops, and a standard iterator otherwise). So the generated code is usually
much faster than what Pyrex gives you. Robert and I had an optimise session
lately where we dropped the function call-overhead by some 20-50% (!) compared
to the preceding Cython version (not even to Pyrex), just depending on the
signature.

I think that qualifies for an optimising compiler.

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for library to estimate likeness of two strings

2008-02-07 Thread Guilherme Polo
2008/2/7, [EMAIL PROTECTED] [EMAIL PROTECTED]:
 On Feb 7, 2:37 am, Daniel Fetchinson [EMAIL PROTECTED]
  wrote:

  Hi folks, just went through this thread and a related one from 2006
   and I was wondering what the best solution is for using these string
   metrics in a database search. If I want to query the database for a
   string or something that is close to it (close being defined by one of
   the string metrics discussed above) it seems I have to select each and
   every word from the database and compare it with the query word which
   is very ineffective.


 I have never used sqlite database, but Postgres has a module that
  implements levenshtein(), soundex() and metaphone() functions, so you
  can do something like this:

  SELECT * FROM s WHERE soundex(name) = soundex('john');
  SELECT * FROM s WHERE difference(name, 'john')  2;

  http://www.postgresql.org/docs/8.3/static/fuzzystrmatch.html


SQLite supports soundex, but it is disabled by default, you need to
compile it with -DSQLITE_SOUNDEX=1

 --
  http://mail.python.org/mailman/listinfo/python-list



-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to use .NET DLL from Python

2008-02-07 Thread Christian Heimes
Luis M. González wrote:
 Oh, I know what you mean.
 But that was exactly the reason for having a .DLLs folder, isn't it?
 When you place an assembly into this folder, you avoid having to write
 this boilerplate code, and simply import the assembly as you would
 with a normal python module. At least, that´s how it worked in
 previous versions...

In IronPython and with PythonDotNET you can import namespaces. Assembly
names and name spaces don't have to be related. E.g. ClassLibrary1.dll
may provide the namespace ClassLibA and ClassLibB.
clr.AddReference('ClassLibrary1') loads the assembly 'ClassLibrary1' and
makes all namespaces available to Python.

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why not a Python compiler?

2008-02-07 Thread [EMAIL PROTECTED]
On Feb 7, 9:06 am, Steve Holden [EMAIL PROTECTED] wrote:
 Ryszard Szopa wrote:
  On Feb 5, 9:30 am, [EMAIL PROTECTED] wrote:

  I don't know the exact details but I think the issue is the dynamic
  nature of Python makes it impossible to correctly store the various
  types and changes into compiled code. Someone else will probably be
  able to provide a good reason as to why it isn't very feasible, nor a
  good idea. If you want to speed up your python look at 
  Psyco.http://psyco.sourceforge.net/

  Yeah, but exactly what features make it so hard to write a compiler
  for Python?
  [...]

 a. People tell me writing a compiler for Python is hard.

 b. It's certainly way to hard for me.

 c. But hey, I've heard about this neat language called Common Lisp that
 has a compiler. It looks a lot like Python.

 d. So why can't you brainboxes write a compiler for Python?

 Please tell me if I'm missing anything from this summary of your thought
 processes.


The basic difference is in point c. Common Lisp was a standard arrived
at by discussions including people who spent the 1970s and 1980s
developing high-performance native-code Lisp compilers targeting
conventional architectures (e.g. PDP-10, VAX, Sun workstations, etc.).
Stuff that would be hard to support with compiled code on conventional
CPUs was discouraged by the process.

The semantics of the Common Lisp standard were developed with the
needs of compilers in mind. CLOS is a very powerful object system, but
the design was developed with compilation and efficiency concerns in
mind. One major difference from Python OOP (as I understand it): CLOS
methods are looked up by their global method name. Python methods
(IIRC) are looked up in per-instance dictionaries. Redefining CLOS
methods requires changing one method-dispatch cache, and is supported
through a high-level interface, which a compiler can translate into
the low-level implementation machinery. Python code can mash the
dictionaries at will, because the low-level machinery is exposed.

The details, if I have mis-stated them, are not as important as the
principle of original design intent I am trying to illustrate.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket script from perl - python

2008-02-07 Thread Jerry Hill
On Feb 7, 2008 9:39 AM, kettle [EMAIL PROTECTED] wrote:
 f = open('/home/myuname/socket.wav','rb')
 audio = 
 for line in f:
 audio += line

I don't know anything about socket programming in python, but this bit
doesn't seem right for working on a binary file.  You should just read
all of the data into audio in one go, like this:

f = open('/home/myuname/socket.wav','rb')
audio = f.read()

There's no need to iterate over the lines in the file, since it's
quite likely that there really aren't any 'lines' in a binary file.

-- 
Jerry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Must COMMIT after SELECT

2008-02-07 Thread M.-A. Lemburg
On 2008-02-07 14:29, Steve Holden wrote:
 Paul Boddie wrote:
 With PostgreSQL, my impression is that the intended way of using
 cursors is not entirely compatible with the DB-API: you declare
 cursors only when you know what the query will be, not in advance, and
 they can only be used with certain kinds of operations. As far as I
 recall, pyPgSQL supports cursors fairly transparently, albeit through
 various ad-hoc measures, whereas psycopg2 only does so for named
 cursors - a concept missing from the DB-API as far as I can see.

 Yes, unfortunately the nomenclature of the DB API conflicts with that of 
 SQL'S DECLARE CURSOR, where the named cursor is effectively a sequence 
 of query results that (under certain isolation levels and patterns of 
 usage) can reflect database changes as they occur. Different 
 implementers have chosen different relationships between DB API cursors 
 and SQL cursors since it was introduced in the SQL 92 standard.
 
 I believe, without documentary justification, that named cursors were 
 introduced into SQL to support stored procedures, and therefore weren't 
 intended to be used for queries whose results were communicated outside 
 the server.

Cursors defined using DECLARE CURSOR usually live in the
scope of the database engine. They are different from the cursors
defined and used with the database APIs.

MS even warns against mixing them:

http://msdn2.microsoft.com/en-us/library/aa172576(SQL.80).aspx

The Python DB-API is defined at the database API level, so the
same applies in the context of DB-API cursors.

In practice, I've not had problems with accessing named cursors
using DB-API cursors.

The main reason for the MS warning is that
cursors can be used for lots of interesting optimizations
such as auto-updating result sets and scrolling, positioned
updates or deletions, etc. The DB-API doesn't expose all these
nifty features, so doesn't easily run into trouble.

mxODBC has support for named cursors that you can later
use for positioned updates. You declare the name of the
cursor when creating it:

cursor1 = connection.cursor('mycursor')
cursor1.execute('select id, name, value from mytable')

# Position the mycursor on row 10
cursor1.fetchmany(10)

# Update row 10
cursor2 = connection.cursor()
cursor2.execute('update mytable set value = ? where current of mycursor')

cursor1.close()
cursor2.close()

However, it's usually better to do updates in the classical
way, ie. by referencing a primary key.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Feb 07 2008)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for library to estimate likeness of two strings

2008-02-07 Thread [EMAIL PROTECTED]
On Feb 7, 2:37 am, Daniel Fetchinson [EMAIL PROTECTED]
wrote:
 Hi folks, just went through this thread and a related one from 2006
 and I was wondering what the best solution is for using these string
 metrics in a database search. If I want to query the database for a
 string or something that is close to it (close being defined by one of
 the string metrics discussed above) it seems I have to select each and
 every word from the database and compare it with the query word which
 is very ineffective.

I have never used sqlite database, but Postgres has a module that
implements levenshtein(), soundex() and metaphone() functions, so you
can do something like this:

SELECT * FROM s WHERE soundex(name) = soundex('john');
SELECT * FROM s WHERE difference(name, 'john')  2;

http://www.postgresql.org/docs/8.3/static/fuzzystrmatch.html
-- 
http://mail.python.org/mailman/listinfo/python-list


CVS access with Python

2008-02-07 Thread Ravi Kumar
I have to design a Web-based CVS client. I could not find any module,
cvs-binding in python.

I have investigated all sort of Web Interface, including Sandweb, and
ViewCVS etc.
But these provide Read-only access and features. I need to provide almost
all sort of basic features a developer frequently need in it.
So please guide me.
I found javacvs project in Netbeans project repository which seems a nice
library, but since I am not a java programmer, this fails to me.

Other problem is its implementation. Say, there is a repository of some
projects with many modules. Now, when one developer wants to checkout, I can
get the revision Sources to Web-server temporary sandbox, and create an
archive (tar.gz/zip) and put that for downloading by the user. Since there
is many-to-many relation between projects and developers, it will consume a
lot of disk space on Web-server, creating 'n' copies of a single project for
'n' users, and assume all developers are checking out all sources. God
knows.
So is there any good implementation for such situation.

-- 
-=Ravi=-
-- 
http://mail.python.org/mailman/listinfo/python-list

ANN: ConfigObj 4.5.1 and validate 0.3.1

2008-02-07 Thread Fuzzyman
After one year and two days since the last release, there is a new
release of ConfigObj.

* ConfigObj 4.5.1 http://www.voidspace.org.uk/python/configobj.html
* Validate 0.3.1 http://www.voidspace.org.uk/python/validate.html

This release adds a few new features, plus has several bugfixes and
minor performance improvements.
Thanks to all those who gave feedback, reported bugs and provided
patches.


What are ConfigObj and Validate?
=

**ConfigObj** is a simple to use but powerful configuration file
management library.
Features include:

* Nested sections to any depth
* Unicode support
* List and multiline values
* Integrated with a powerful validation system

- including automatic type checking/conversion
- repeated sections
- and allowing default values

* All comments in a file are preserved when writing
* The order of keys/sections is preserved
* A powerful unrepr mode for storing basic datatypes

**validate** is the module (optional) used for config file validation
and type marshalling. It
can be used outside of ConfigObj for matching string values against a
text specification which
also does type conversion.


Changes in ConfigObj 4.5.1


Distribution updated to include version 0.3.1 of validate. This means
that
Unicode configspecs now work.

ConfigObj will now guarantee that files will be written terminated
with a
newline.

ConfigObj will no longer attempt to import the ``validate`` module,
until/unless
you call ``ConfigObj.validate`` with ``preserve_errors=True``. This
makes it
faster to import.

New methods ``restore_default`` and ``restore_defaults``.
``restore_default``
resets an entry to its default value (and returns that value).
``restore_defaults``
resets all entries to their default value. It doesn't modify entries
without a
default value. You must have validated a ConfigObj (which populates
the
``default_values`` dictionary) before calling these methods.

BUGFIX: Proper quoting of keys, values and list values that contain
hashes
(when writing).  When ``list_values=False``, values containing hashes
are
triple quoted.

Added the ``reload`` method. This reloads a ConfigObj from file. If
the filename
attribute is not set then a ``ReloadError`` (a new exception
inheriting from
``IOError``) is raised.

BUGFIX: Files are read in with 'rb' mode, so that native/non-native
line endings work!

Minor efficiency improvement in ``unrepr`` mode.

Added missing docstrings for some overridden dictionary methods.

Added the ``reset`` method. This restores a ConfigObj to a freshly
created state.

Removed old CHANGELOG file.


Changes in Validate 0.3.1
==

BUGFIX: Unicode checks no longer broken.

Improved performance with a parse cache.

New ``get_default_value`` method. Given a check it returns the default
value (converted to the correct type) or raises a ``KeyError`` if the
check doesn't specify a default.

Added 'tuple' check and corresponding 'is_tuple' function (which
always returns a tuple).

BUGFIX: A quoted 'None' as a default value is no longer treated as
None,
but as the string 'None'.

BUGFIX: We weren't unquoting keyword arguments of length two, so an
empty string didn't work as a default.

BUGFIX: Strings no longer pass the 'is_list' check. Additionally, the
list checks always return lists.

A couple of documentation bug fixes.

Removed CHANGELOG from module.


Michael Foord
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for library to estimate likeness of two strings

2008-02-07 Thread JKPeck
On Feb 7, 6:11 am, Lee Capps [EMAIL PROTECTED] wrote:
 At 14:01 Wed 06 Feb 2008, [EMAIL PROTECTED] wrote:

 Are there any Python libraries implementing measurement of similarity
 of two strings of Latin characters?

 I'm writing a script to guess-merge two tables based on people's
 names, which are not necessarily spelled the same way in both tables
 (especially the given names).  I would like some function that would
 help me make the best guess.

 Many thanks in advance!

 I used difflib.get_close_matches for something similar:

 http://docs.python.org/lib/module-difflib.html

 HTH.

 --
 Lee Capps
 Technology Specialist
 CTE Resource Center

Algorithms typically used for name comparisons include soundex,
nysiis, and levenshtein distance.  The last is more general and
variations are used in spell checkers.  You can probably Google for
Python versions.  You can find implementations of these comparison
functions at
www.spss.com/devcentral in the extendedTransforms.py module.
(Requires a login but free).

HTH,
Jon Peck
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: index() of sequence type?

2008-02-07 Thread Steve Holden
Neal Becker wrote:
 I see list has index member, but is there an index function that applies to
 any sequence type?
 
 If not, shouldn't there be?
 
Hitler would doubtless have wanted one.

regards
  Steve
[who knows this is a futile and incorrect attempt to have this thread 
suffer from premature termination].
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Steve Holden
Denis Bilenko wrote:
 Tim Golden wrote:
 
 Dodging your question slightly (and at the risk of teaching
 my grandmother to suck eggs) I sometimes use this idiom for
 checking params. Obviously it only goes so far, but it's
 fairly compact:
 
 Noddy example code
 import os, sys
 
 if __name__ == '__main__':
   ARGS = None, DEV
   filename, db = \
 (j or i for i, j in map (None, ARGS, sys.argv[1:]))
 
   print sys.argv
   print filename, db
 
 /code
 
 Thank you for the example. It demonstrates perfectly how
 much people miss this feature :)
 
 
 Raymond Hettinger wrote:
 
 At first blush that example would make it seem like a good idea, but I
 don't see how the example could extend past the first index.  If the
 port argument is optional, how would you know the index position of
 optional arguments to follow?
 
 With a dictionary, one could plausibly write:
 
  host = d.get('host', 'http://example.com')
  port = d.get('port', 8080)
  path = d.get('path', '/')
 
 But would this make sense with a list:
 
  host = s.get(0, 'http://example.com')
  port = d.get(1, 8080)
  path = d.get(2, '/')
 
 If positions 0 and 1 are optional, how do you expect to know whether
 path is going to be at position 2?  This problem doesn't exist with
 dictionaries because the presence or absence of optional entries does
 not affect the key reference to other entries.  Accordingly, I
 wouldn't expect that dict.get() would have a parallel list.get() with
 plausible use cases.
 
 If you want to fill position 2, then positions 0 and 1 are mandatory.
 It is the simplest possible option parsing, I didn't said it was the
 most flexible :)
 
 But perhaps it was a wrong example altogether.
 
 Consider a couple more snippets, unrelated to command-line options.
 (found by searching 'IndexError' in the python standard library)
 
 this snippet from cmd.py:
 
 try:
 return self.completion_matches[state]
 except IndexError:
 return None
 
 transforms into
 
 return self.completion_matches.get(state)
 
 
 another one from fileinput.py
 
 try:
 line = self._buffer[self._bufindex]
 except IndexError:
 pass
 else:
 self._bufindex += 1
 self._lineno += 1
 self._filelineno += 1
 return line
 line = self.readline()
 
 becomes
 
 line = self._buffer.get(self._bufindex)
 if line:
 self._bufindex += 1
 self._lineno += 1
 self._filelineno += 1
 return line
 line = self.readline()
 
These versions differ with respect to treatment of blank lines, which 
indicates  how easy it is to go astray in this kind of semantic 
optimization. Your example simply wouldn't work (though you could patch 
it up using if line is None. (despite the use of short-circuiting 
predicates).

 both examples show reduction by 3 lines.
 
Perhaps so, but you have to realise that Python has never valued code 
compactness over clarity.

 There's nothing dictionary-specific in 'get', it is
 just a special use-case of '__getitem__' that is needed frequently.
 Since list has '__getitem__' it deserves to have 'get' too.

I'm not sure that your democratic wish to ensure fairness to sequences 
will garner much support, interesting though it is in an academic sense.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-07 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 Steven D'Aprano:
 With the greatest respect, I think that if you think the second example
 is more clear, you're completely bonkers. *grins*
 
It's amusing how often with the greatest respect is used to preface a 
statement that clearly implies very little respect at all. Though, for 
what it's worth, I agree with Steven here.

 No one is completely normal, I presume :-)
 I'd like to know what others think about it, about this anti-feature.
 What I can say is that other computer languages too think that boolean
 operations must return boolean values only, so I am not alone in my
 folly :-)
 
Other languages do indeed refuse the temptation to short-circuit, but 
that doesn't mean that Python is wrong to do so. It's a design choice, 
and while you are free to disagree with it I imagine you would be 
pissing in the wind in attempting to get a change like that into Python 3.

Most people like the semantics of and and or as they are.

no-more-normal-than-anyone-else-ly y'rs  - steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-07 Thread Steve Holden
Ryszard Szopa wrote:
 On Feb 5, 9:30 am, [EMAIL PROTECTED] wrote:
 
 I don't know the exact details but I think the issue is the dynamic
 nature of Python makes it impossible to correctly store the various
 types and changes into compiled code. Someone else will probably be
 able to provide a good reason as to why it isn't very feasible, nor a
 good idea. If you want to speed up your python look at Psyco. 
 http://psyco.sourceforge.net/
 
 Yeah, but exactly what features make it so hard to write a compiler
 for Python?
 [...]

a. People tell me writing a compiler for Python is hard.

b. It's certainly way to hard for me.

c. But hey, I've heard about this neat language called Common Lisp that 
has a compiler. It looks a lot like Python.

d. So why can't you brainboxes write a compiler for Python?

Please tell me if I'm missing anything from this summary of your thought 
processes.

regards
   Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting all user defined attributes of a class

2008-02-07 Thread George Sakkis
On Feb 7, 1:42 pm, Amit Gupta [EMAIL PROTECTED] wrote:

 Thanks. What I found is: If I call iterate over the __dict__ of the
 instance of the class, I only get user-atttributes and not built-in
 attributes. I have an instance of that class, anyway, so this will do.
 However, I wonder if I am getting just lucky and this might change in
 future. In that regard the solution provides by all posters above
 might well be more robust.

Instances and classes have separate namespaces:

class X(object):
x = 1
def __init__(self):
self.y = 2

 X().__dict__
{'y': 2}
 X.__dict__
dictproxy object at 0xb7beab9c

 X.__dict__.items()
[('__module__', '__main__'),
 ('__dict__', attribute '__dict__' of 'X' objects),
 ('x', 1),
 ('__weakref__', attribute '__weakref__' of 'X' objects),
 ('__doc__', None),
 ('__init__', function __init__ at 0xb7b5a454)]

And neither of those includes attributes defined in superclasses,
classes with __slots__,  pseudo-attributes through __getattr__ and
possibly more I've missed.

George
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dear David (was: MyHDL project)

2008-02-07 Thread ajaksu
On Feb 7, 4:48 pm, Blubaugh, David A. [EMAIL PROTECTED] wrote:
  sir,

 Is there still a possibility to collaborate???

 David Blubaugh

Dear David A. Blubaugh,
Could you please make it a little less painful to read your messages?
You're giving a bad name to Belcan, too.

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a trick with lists ?

2008-02-07 Thread Steve Holden
Tim Chase wrote:
 self.tasks[:] = tasks

 What I do not fully understand is the line self.tasks[:] = tasks. Why 
 does 
 the guy who coded this did not write it as self.tasks = tasks? What is 
 the 
 use of the [:] trick ?
 It changes the list in-place. If it has been given to other objects, it 
 might require that.
 Nowadays it's stylistically better to write

  self.tasks = list(tasks)

 as it does just the same and makes it a little clearer what's going on 
 
 Um...except it's not just the same?
 
class Foo(object):
  def __init__(self, tasks):
self.tasks1 = tasks
self.todo1 = [self.tasks1, 42]
self.tasks2 = tasks
self.todo2 = [self.tasks2, 42]
  def new_tasks1(self, tasks):
self.tasks1 = list(tasks)
  def new_tasks2(self, tasks):
self.tasks2[:] = list(tasks)
  def __str__(self):
return %r\n%r % (self.todo1, self.todo2)
 
f = Foo([1,2,3])
 
f.new_tasks1([4,5,6])
print 'task1'
print f # todo1/2 haven't been changed
 
print 'task2'
f.new_tasks2([4,5,6])
print f # both todo 1  2 have been changed
 
 Assignment to a name just rebinds that name.  Assignment to a 
 slice of a list replaces the contents in-place.
 
[sigh] Right, I got the assignment the wrong way around (and clearly you 
can't put list(tasks) on the left-hand side of an assignment).

Of course

 self.tasks = list(tasks)

is equivalent to

 self.tasks = tasks[:]

Thanks for pointing out my error.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distinguishing between functions and methods in a decorator.

2008-02-07 Thread Arnaud Delobelle
On Feb 7, 4:10 pm, Berteun Damman [EMAIL PROTECTED] wrote:
 Hello,

 I was wondering a bit about the differences between methods and
 functions. I have the following:

 def wrap(arg):
 print type(arg)
 return arg

 class C:
 def f():
 pass

 @wrap
 def g():
 pass

 def h():
 pass

 print type(C.f)
 print type(h)

 Which gives the following output:
 type 'function'
 type 'instancemethod'
 type 'function'

 The first line is caused by the 'wrap' function of course. I had
 expected the first line to be 'instancemethod' too. So, I would guess,
 these methods of C are first created as functions, and only then become
 methods after they are 'attached' to some classobj. (You can do that
 yourself of course, by saying, for example, C.h = h, then the type of
 C.h is 'instancemethod' too.)

 Why does the wrapping occur before the function is 'made' into an
 instancemethod?

Consider this:

 class Foo(object):
... def bar(self): pass
...
 Foo.bar
unbound method Foo.bar
 Foo.__dict__['bar']
function bar at 0x7d5b0


It shows that when Foo.bar is evaluated, a new instancemethod object
is created and that the 'bar' in the dictionary of 'Foo' is forever a
plain function object.  In fact, Foo.bar is equivalent to
Foo.__dict__['bar'].__get__(None, Foo):

 Foo.__dict__['bar'].__get__(None, Foo)
unbound method Foo.bar


For more details you can read 
http://users.rcn.com/python/download/Descriptor.htm.

 The reason for asking is that I would like to differentiate between
 wrapping a function and an instancemethod, because in the latter case,
 the first parameter will be the implicit 'self', which I would like to
 ignore.  However, when the wrapping occurs, the method still looks like
 a function.

 Berteun

I think you're better off having a 'wrap' decorator for functions and
a 'wrapmethod' decorator for methods.

HTH

--
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >