Re: Possible constant assignment operators ":=" and "::=" for Python

2006-05-04 Thread Fredrik Lundh
Christophe wrote:

> That's easy, since A is a symbolic constant know at compile time, and
> since it's a known mutable objet, the code once compiled will be
> equivalent to:
>
>  >>> b = [[]]
>
>  >>> # much later
>  >>> b|0].append('1')

the OP talked about constants as names for immutable objects, not pre-
processor macros.  but alright, using the "symbolic constant" approach,
what would this print ?

>>> def foo(var):
... var.append('1')
... print var
...
>>> b = []
>>> foo(b)
>>> foo(b)

and this ?

>>> constant A = []
>>> print A is A





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


Re: Possibly dumb question about dicts and __hash__()

2006-05-04 Thread Joel Hedlund
Hi!

 > Just the hash is not enough. You need to define equality, too:

Thanks a million for clearing that up.

Cheers!
/Joel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stripping unwanted chars from string

2006-05-04 Thread bruno at modulix
Edward Elliott wrote:
> Bryan wrote:
> 
>> >>> keepchars = set(string.letters + string.digits + '-.')
> 
> 
> Now that looks a lot better.  Just don't forget the underscore. :)
> 
You may also want to have a look at string.translate() and
string.maketrans()

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This coding style bad practise?

2006-05-04 Thread bruno at modulix
Carl Friedrich Bolz wrote:
> Bruno Desthuilliers wrote:
> 
>> Martin P. Hellwig a écrit :
>>
>>> I created a class which creates a relative unique id string, now my
>>> program just works fine and as expected but somehow I get the feeling
>>> that I misused the __repr__ since I guess people expect to 'execute'
>>> a function in an instance instead of using it's representation string
>>> of the instance itself, could you elaborate whether you find this bad
>>> practice and if yes what would have been a better way to do it?
>>
>>
>> Why not just use the call operator instead ? ie:
>>
>>  >>> id = IDGenerator(...)
>>  >>> id()
>> 01_20060424_151903_1
>>  >>> id()
>> 01_20060424_151905_2
> 
> 
> because that shadows a builtin?

oops :(

> sorry, could not resist :-)


idgen = IDGenerator(...)
idgen()



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This coding style bad practise?

2006-05-04 Thread bruno at modulix
Martin P. Hellwig wrote:
> Bruno Desthuilliers wrote:
> 
> 
>>
>> Why not just use the call operator instead ? ie:
>>
>>  >>> id = IDGenerator(...)
>>  >>> id()
>> 01_20060424_151903_1
>>  >>> id()
>> 01_20060424_151905_2
>>
> 
> Because of:
> 
> id = IDGenerator("01",99)
> id()
>>
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> id()
>> TypeError: 'IDGenerator' object is not callable
>>
>

Of course - you have to overload the call operator for this to work.
Just rename IDGenerator.__repr__ to IDGenerator.__call__, and I garantee
this will work - and will be *much* more cleaner than abusing __repr__.



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pythonic way to sort

2006-05-04 Thread Boris Borcic
Jay Parlar wrote:
> 
> On May 4, 2006, at 12:12 AM, [EMAIL PROTECTED] wrote:
> [...]

> Assume that you have the lines in a list called 'lines', 
> as follows:
> 
> lines = [
>"1SOME STRING  ~ABC~12311232432D~20060401~",
>"3SOME STRING  ~ACD~14353453554G~20060401~",
>"2SOME STRING  ~DEF~13534534543C~20060401~"]
> 
> 
> The more traditional way would be to define your own comparison function:
> 
> def my_cmp(x,y):
> return cmp( x.split("~")[1], y.split("~")[1])
> 
> lines.sort(cmp=my_cmp)
> 
> 
> The newer, faster way, would be to define your own key function:
> 
> def my_key(x):
> return x.split("~")[1]
> 
> lines.sort(key=my_key)

and if the data is in a file rather than a list, you may write eg

lines = sorted(file("/path/tofile"),key=mike)

to create it sorted.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: noob question: "TypeError" wrong number of args

2006-05-04 Thread bruno at modulix
Ben Finney wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> 
> 
>>Ben Finney a écrit :
>>
>>>So now you're proposing that this be a special case when a
>>>function is declared by that particular syntax, and it should be
>>>different to when a function is created outside the class
>>>definition and added as a method to the object at run-time.
>>>
>>>Thus breaking not only "explicit is better than implicit",
>>
>>This one can be subject to discussion.
> 
> 
> All the assertions in 'import this' are subject to discussion. 

Of course - but that was not the point. I meant that having implicit
self in methods would not break this assertion much more than the
current strange mix of explicit declaration of self + implicit passing
of self.

> They're
> even contradictory.

That's the nature of Zen, isn't it ?-)

(snip)

>>I'm not yet ready to vote for Edward's proposition - as you say, it
>>makes 'def statements into a class statement' a special case, and I
>>don't like special cases too much (OTOH, there actually *are*
>>special cases - __new__() being an example) - *but* it's not that
>>silly either IMHO, and I think this should not be dismissed on a
>>purely reactional basis.
> 
> 
> My basis for rejecting the proposal is that it claims to offer net
> simplicity, yet it breaks at least two of the admonishments that
> simplify Python.

One could also claim that the current scheme *actually* breaks
explicit-implicit and special-case rules in that the instance is
implicitely passed at call time for the  bound methods special case -
which is ok IMHO since practicallity-beats-purity. Also, FWIW, Edward's
proposition can be justified (at least that's Edward's POV) by the first
rule : beautiful is better than ugly !-)

disclaimer : None of this is to be taken as the expression of my own
position on this proposition...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list

Displaying Images and getting input from Mouse

2006-05-04 Thread Wynand Singels
Hi there everyone

I'm trying to figure out the best (and fastest way) to display a JPEG image
and then input several (x,y) coordinate pairs from mouse clicks on the
image.

I figured out how to do this in pylab using matplotlib as follows:

img = 256 - S.misc.pilutil.imread('pic1.jpg')
P.imshow(img)
P.connect('button_press_event',click)
P.show()

The function click() gets the coordinates form the event.xdata and
event.ydata, but this is very slow and cumbersome. 

The other option I was looking at was using wxPython - a staticbitmap with
EVT_LEFT_DOWN or something like that. But I'm struggling to get this to
work. I also looked at the Python Image Library (PIL) but there does not
seem to be one conclusive way of doing this.

Please take into account that my end product will have to have a full GUI.

Is there some other package I can use? Or am I missing some part of wxPython
that can do this? Is there anyone that has done anything similar?

Wynand

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


Re: Because of multithreading semantics, this is not reliable.

2006-05-04 Thread Christophe
[EMAIL PROTECTED] a écrit :
> Tim and Grant
> 
> 
>  if q.empty():
>  return
> 
> 
> Of course you explanation is understood and ideally should be included
> as a note in the Python documentation.  And the "not reliable" should
> be removed from the documentation!
> 
> Anyway, many thanks for your explanations (I feel "safer" now).
> 
> Olaf
> 

You could go as far as to say that since the function return itself 
isn't wrapped in a mutex, the value can be obsolete before even the 
function returns.

ie that code can sometimes return the wrong value :

def empty(self):
 self.acquire_mutex()
 result = self.count == 0
 self.release_mutex()
 return result   before that line, some other thread added a value !
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: noob question: "TypeError" wrong number of args

2006-05-04 Thread bruno at modulix
Edward Elliott wrote:
> Ben Finney wrote:
> 
>>As I understand it, the point was not what the code does, but to give
>>a sample input (a Python program) for the "simple text processor" you
>>described to wade through.
> 
> 
> Ah, well then, there's no need for a full-blown parser.  It should suffice
> to recognize a class definition and modify the parameter list of every def
> indented one level further than that.

won't do :

class CounterExample(object):
  if compute_some_const_according_to_phase_of_moon():
def meth(...):
  do_something(self, 42)
  else:
do_something_else(self)


>  Then pick out the static methods and
> 'undo' those.

don't forget classmethods...


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible constant assignment operators ":=" and "::=" for Python

2006-05-04 Thread Christophe
Fredrik Lundh a écrit :
> Christophe wrote:
> 
> 
>>That's easy, since A is a symbolic constant know at compile time, and
>>since it's a known mutable objet, the code once compiled will be
>>equivalent to:
>>
>> >>> b = [[]]
>>
>> >>> # much later
>> >>> b|0].append('1')
> 
> 
> the OP talked about constants as names for immutable objects, not pre-
> processor macros.  but alright, using the "symbolic constant" approach,
> what would this print ?
> 
> >>> def foo(var):
> ... var.append('1')
> ... print var
> ...
> >>> b = []
> >>> foo(b)
> >>> foo(b)

I think you've made a mistake in your example. This is valid today's 
Python you know :) And it'll print more or less :
['1']
['1', '1']

> and this ?
> 
> >>> constant A = []
> >>> print A is A

Obviously, False.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Customize IE to make a toolbar visible

2006-05-04 Thread Roger Upole
This does the trick for Google toolbar:

import win32com.client
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1
ie.ShowBrowserBar('{2318C2B1-4965-11d4-9B18-009027A5CD4F}',True,0)

You should be able to just substitute the GUID for the Yahoo toolbar.

  Roger


<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Does anyone know of a way to make a toolbar visible in IE through
> automation? I am not speaking about the InternetExplorer.ToolBar that I
> have run into on MSDN, but rather want to make a toolbar such as
> Yahoo's visibilbe through running my script.
>
> How would I do this.
>
> Thanks,
> Dave
> 


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


Re: Dispatching operations to user-defined methods

2006-05-04 Thread Michele Simionato
Apparently Guido fell in love with generic functions, so (possibly)  in
future Python
versions you will be able to solve dispatching problems in in an
industrial strenght
way. Sometimes however the simplest possible way is enough, and you can
use
something like this :

class SimpleDispatcher(object):
"""A dispatcher is a callable object that looks in a "namespace"
for callable objects and calls them with the signature

``(, , <*args>, <**kw>)``

The "namespace" can be a module, a class, a dictionary, or anything
that responds to ``getattr`` or (alternatively) to ``__getitem__``.

Here is an example of usage:

>>> call = SimpleDispatcher(globals())

>>> def manager_showpage():
...return 'Manager'

>>> def member_showpage():
... return 'Member'

>>> def anonymous_showpage():
... return 'Anonymous'

>>> call('showpage', 'anonymous')
'Anonymous'
>>> call('showpage', 'manager')
'Manager'
>>> call('showpage', 'member')
'Member'
"""
def __init__(self, ns):
self._ns = ns
def __call__(self, funcname, classname, *args, **kw):
try:
func = getattr(self._ns, '%s_%s' % (classname, funcname))
except AttributeError:
func = self._ns['%s_%s' % (class

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


Fw: Swaying A Coder Away From Python

2006-05-04 Thread Tim Williams
- Original Message -
From: DevWebProUK  [EMAIL PROTECTED]
To:
Sent: Wednesday, May 03, 2006 10:14 PM
Subject: Swaying A Coder Away From Python

Swaying A Coder Away From Python

By David A. Utter

One programmer blogged about the powerful attraction he is feeling to
C# programming, anddeparting from six years of
tinkering with Python. On a higher level, a battle between Python and
C# could be seen as Google versus Microsoft, since Python's creator
Guido van Rossum joined Google in December 2005. But legions of  C#
developers in Redmond may be content to bring over other Python
devotees one at a time.

Michal Wallace would be one of those Python followers. He has spent
the past severalyears in Python's embrace. Judging
from a recent post  Wallace made, he's found a knife named C# and is
ready to cut  himself free from Python, for a few reasons.

"One problem is that python tools suck," he wrote. Wallace compared 
the various IDEs and other developer tools available to Microsoft's
freely available Visual Studio Express and called them "toys."

He also  listed a few reasons why C# appeals to him over Python or Java:


� anonymous functions (delegates)
�  a python-like  yield statement
�  a nice type system with generics
�  interfaces
�  properties(Yay!!)
Wallace also cited the "huge number of developers" doing .Net as
another reason to switch to C#.   "Thanks to Microsoft's reach, .NET
is a much bigger pond than python. I can hire .NET developers
anywhere, or if i want, I  can get a job as a .NET developer," he
wrote.



IBM developer and well-known Apache contributor Sam Ruby suggested
diversification is the way to happiness: "My first recommendation
aligns with Aristotle's: diversify. I didn't doany
Perl in the past week, but I did do Python, PHP, Ruby, and 
JavaScript. In pond size terms, PHP is huge and growing."

Burningbird blogger Shelley Powers sees some problems with the P
section of ONLamp, consisting of Python,Perl, and PHP. Based on
her perspective,  "in St. Louis, the demand is for .NET (VB or C#) or
Java.   That's it. I mean, that's really it. Most of the other work in
   PHP or Python or Perl is off-shored.

Microsoft's Don Dodge blogged about .NET's strong points for C#
developers: Microsoft.Net is now the most popular
development platform in the world. It supports lots of different
languages, has an awesome IDE, and integrates with slick QA and code
management tools.The .Net community provides tons
of support, code samples,test cases, and advice.

Now Wallace has arguments for and against the switch.

   
   About the Author:
David Utter is a staff  writer for WebProNews covering business an  technology.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Possible constant assignment operators ":=" and "::=" for Python

2006-05-04 Thread Michele Simionato
Edward Elliott wrote:
> Michele Simionato wrote:
> > Python solution is to rely on the intelligence of programmers. If they
> > see an all caps name and then they try to change it without knowing what
> > they are doing, then they are stupid. If you have stupid programmers there
> > is no way the language can stop them for making disasters.
>
> Which doesn't apply here, one of the OP's examples further up this thread
> doesn't modify any ALL CAPS vars directly:
>
> >>> A = []  # let's declare a "constant" here
> >>> b = A   # and let's assign the constant here
> >>> b.append('1') # OOPS!

But it makes no sense to use a mutable object for a constant!
The user should use a tuple, or a custom list-like type where
all methods with side effects are removed, so it effectively acts
as a tuple.

  Michele Simionato

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


Re: stripping unwanted chars from string

2006-05-04 Thread John Machin
On 4/05/2006 4:30 PM, Edward Elliott wrote:
> Bryan wrote:
>>  >>> keepchars = set(string.letters + string.digits + '-.')
> 
> Now that looks a lot better.  Just don't forget the underscore. :)
> 

*Looks* better than the monkey business. Perhaps I should point out to 
those of the studio audience who are huddled in an ASCII bunker (if any) 
that string.letters provides the characters considered to be alphabetic 
in whatever the locale is currently set to. There is no guarantee that 
the operating system won't permit filenames containing other characters, 
ones that the file's creator would quite reasonably consider to be 
alphabetic. And of course there are languages that have characters that 
one would not want to strip but can scarcely be described as alphanumeric.

 >>> import os
 >>> os.listdir(u'.')
[u'\xc9t\xe9_et_hiver.doc', u'\u041c\u043e\u0441\u043a\u0432\u0430.txt', 
u'\u5f20\u654f.txt']

 >>> import string
 >>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Doing
import locale; locale.setlocale(locale.LC_ALL, '')
would make string.letters work (for me) with the first file above, but 
that's all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of variables

2006-05-04 Thread Gary Wessle
Ryan Forsythe <[EMAIL PROTECTED]> writes:

> Gary Wessle wrote:
> > the example was an in-accuretlly representation of a the problem I am
> > having. my apologies.
> > 
> > a = []
> > def prnt():
> >print len(a)
> > 
>  prnt
> > 
> > 
> > I expect to get 0 "the length of list a"
> 
> You want prnt(), not prnt:
> 

I finally was able to duplicate the error with a through away code
as follows, 


acc = [1,2,3]

def a():
b = [4, 5, 6]
acc = acc + b
print len(acc)

a()

 error 
Traceback (most recent call last):
  File "a.py", line 12, in ?
a()
  File "a.py", line 9, in a
acc = acc + b
UnboundLocalError: local variable 'acc' referenced before assignment
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of variables

2006-05-04 Thread bruno at modulix
Gary Wessle wrote:
> Ryan Forsythe <[EMAIL PROTECTED]> writes:
> 
> 
>>Gary Wessle wrote:
>>
>>>the example was an in-accuretlly representation of a the problem I am
>>>having. my apologies.
>>>
(snip)
> I finally was able to duplicate the error with a through away code
> as follows, 
> 
> 
> acc = [1,2,3]
> 
> def a():
> b = [4, 5, 6]
> acc = acc + b
> print len(acc)
> 
> a()
> 
>  error 
> Traceback (most recent call last):
>   File "a.py", line 12, in ?
> a()
>   File "a.py", line 9, in a
> acc = acc + b
> UnboundLocalError: local variable 'acc' referenced before assignment

This is a FAQ:
http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python

For short: if a name is 'assigned' (in Python, the correct term is
'bound') in the local scope, it'll be considered a local name. If it's
*only* accessed, it'll be looked up in the enclosing namespace - here
the so-called 'global' (which means: 'module') namespace.

The dirty solution is to declare 'acc' as global in the function:
def a():
b = [4, 5, 6]
global acc
acc = acc + b
print len(acc)

but this is really BadCode(tm). As a general rule, functions should not
silently modify or rebind global variables - this leads to maintenance
nightmares. In this case, you should manage to either 1/ pass acc as a
param to a(), or 2/ have a() return the sequence to be added to acc:

# 1
acc = [1,2,3]
def a(alist):
  alist.extend([4, 5, 6])
  return alist

acc = a(acc)
print acc, len(acc)

# 2
acc = [1,2,3]
def a():
  return [4, 5, 6]

acc.extend(a())
print acc, len(acc)


The Right Thing(tm) to do of course depends on the real code, so it may
be yet another solution, but it's impossible to decide with dummy code...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Usage of single click or double click in Tix programming

2006-05-04 Thread praveenkumar . 117
Dear all,
   I am developing an GUI application using Tix
   I want to trigger a window on single or double click on a name
displayed in the GUI.
   How to go about using Python
   your help is very much appreciated
regards
praveen

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


Problem building extension under Cygwin (ImportError: Bad address)

2006-05-04 Thread Lars
Hi,

I have problems building a simple handcoded C-extension (hello.c) with
Cygwin and gcc3.4.4. I hope somebody has encountered the same problem
before, and has some advice.

The extension works just fine with Linux:

gcc -c hello.c -I/usr/local/include/python2.4/
ld -shared hello.o -o hello.so -L /usr/local/lib/ -lpython2.4 -lc
python -c'import hello;q = hello.message("Lars");print q'
Hello, Lars

But doing a similar compile under Cygwin doesn't work so well:
(same options, but the output is called hello.dll and the directories
are a bit different)

$ python -c"import hello"
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: Bad address

btw:
hello.c is from "Programming Python 2nd ed." by Mark Lutz. It's
published by O'Reilly. The code can be downloaded from:
http://examples.oreilly.com/python2/Examples.zip .
hello.c is in the directory PP2E\Integrate\Extend\Hello.


-Lars

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


Re: This coding style bad practise?

2006-05-04 Thread Martin P. Hellwig
bruno at modulix wrote:
> Martin P. Hellwig wrote:
>> Bruno Desthuilliers wrote:
>> 
>>
>>> Why not just use the call operator instead ? ie:
>>>
>>>  >>> id = IDGenerator(...)
>>>  >>> id()
>>> 01_20060424_151903_1
>>>  >>> id()
>>> 01_20060424_151905_2
>>>
>> Because of:
>>
>> id = IDGenerator("01",99)
>> id()
>>> Traceback (most recent call last):
>>>   File "", line 1, in ?
>>> id()
>>> TypeError: 'IDGenerator' object is not callable
>>>
> 
> Of course - you have to overload the call operator for this to work.
> Just rename IDGenerator.__repr__ to IDGenerator.__call__, and I garantee
> this will work - and will be *much* more cleaner than abusing __repr__.
> 
> 
> 
Thanks! That was the thing I was looking for!

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


Re: Swaying A Coder Away From Python

2006-05-04 Thread Fredrik Lundh
Tim Williams wrote:

> By David A. Utter

who's this, and why does he think that sampling some random comments by
some random bloggers should mean anything to anyone ?  (and why do you
seem to think that this matters, btw ?)

(and yes, I recognize the names of some of the bloggers he quotes.  they're
not exactly known for their ability to get things done...  but sure, if you 
cannot
fix yourself, you can always try another language (speaking of which, has any-
one seen Brandon lately? ;-))

instead of wasting time on clueless windbags, I'd recommend Pythoneers to
read something written by someone with a working brain instead:

http://www2.jeffcroft.com/2006/may/02/django-non-programmers/

(which can be summarized as "I hate programming, but that didn't stop me
from building a really cool web application in Python").





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


Re: ZSI usage

2006-05-04 Thread Maxim Sloyko
There is a typo there in functions name. It is called "session_open"
not "open_session", but everything else is as described

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


pleac

2006-05-04 Thread jonas
Hi,

I'm new to python.
After a search on
http://pleac.sourceforge.net/pleac_python/index.html
why python have a low %?

Thanks in advance

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


Re: Zope Guru...

2006-05-04 Thread Nico Grubert
 > In doing some research into Workflow apps regarding document
 > management, I came across Zope. Given that it's Python Based, I
 > figured I'd shout to the group here...

If you want to develop an application with Zope+Python from scratch, 
there are a few Zope products out there that handle workflow 
("DCWorkflow", "Openflow").

If you look for an existing Zope based DMS, you might want to look at 
the "Document Library application" which has been released yesterday by 
infrae. http://www.infrae.com/download/documentlibrary

Another existing Zope based application for document
  management including workflow is "Plone". http://www.plone.org

If you plan to start using Zope 3, you might want to take a look at 
http://www.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/Zope3Workflow


Regards,
   Nico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pleac

2006-05-04 Thread Fredrik Lundh
"jonas" wrote:

> After a search on
> http://pleac.sourceforge.net/pleac_python/index.html
> why python have a low %?

why not ask the pleac maintainers?

(it might be that pythoneers have better things to do with their time
than translating old Perl stuff to Python...  if you want Python cook-
book stuff, start here:

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

)





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


ZSI usage

2006-05-04 Thread Maxim Sloyko
Hi all!
I'm trying to make a simple SOAP call from python to SOAP::Lite (perl)
SOAP server.

My SOAP server has https://myserv.com/open-api URI, the function
open_session has the "QW/API" namespace. SO I do the following:

from ZSI.client import Binding
fp = open('debug.out', 'a')

client = Binding(url='/open-api',
host='myserv.com',
port=443,
ssl=1, tracefile=fp)
client.SetNS("QW/API")
sid = client.open_session(1)

However, I get the following error:

ZSI.FaultException: SOAPAction shall match 'uri#method' if present (got
'""', expected 'QW/API#open_session'

If I look at SOAP packet I see the following:
[snip]

1

[snip]

SO the question is, why ZSI seem to ignore that NS setting? How to fix
that?
Thanks in advance!

--
Maxim

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


Pythoncard question

2006-05-04 Thread DarkBlue
I am trying to port a Delphi database application
to python on linux with a firebird database backend
and I am using pythoncard to recreate the gui.

I will have about 25 delphi forms to
be recreated and I would like to know
what is the best way to call them up
from within each other .
There is a main screen where I must
be able to call up any of the subscreens
and on any given subscreen there would
be buttons to call up 1-5 of the other subscreens
or go back to the mainscreen.

The database is connected on the mainscreen 
and relevant connections/cursors shall be accessible
from any of the subscreens.

While I am able to connect to the database and create the
different screens I am stumped at how to efficiently
call them up and pass the cursors between them as needed.

Sorry for the long post. 


Thanks for any hint
Db 



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


RegEx with multiple occurrences

2006-05-04 Thread Mike
Hi again.

I'm trying to strip all script blocks from HTML, and am using the
following re to do it:

p = re.compile("(\*\)",re.IGNORECASE | re.DOTALL)
m = p.search(data)

The problem is that I'm getting everything from the 1st script's start
tag to the last script's end tag in one group - so it seems like it
parses the string from both ends therefore removing far more from that
data than I want. What am I doing wrong?

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


about the implement of the PyString_InternFromString

2006-05-04 Thread kyo guan
Hi :

Hi guys:

I have a question about the this API.

PyObject *
PyString_InternFromString(const char *cp) {
PyObject *s = PyString_FromString(cp);
if (s == NULL)
return NULL;
PyString_InternInPlace(&s);
return s;
}


Why it always try to call PyString_FromString first?  if char* cp is already in 
the interned dict, this PyString_FromString call is
waster. so I think this API should implement as:

1. check the interned dict
2. if cp is not in the dict, then call PyString_FromString, and insert the new 
string in the dict 3. else : call Py_INCREF and
return.

Is this right?

Kyo.

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


about the implement of the PyString_InternFromString

2006-05-04 Thread Kyo Guan

Hi guys:

I have a question about the this API.

PyObject *
PyString_InternFromString(const char *cp)
{
PyObject *s = PyString_FromString(cp);
if (s == NULL)
return NULL;
PyString_InternInPlace(&s);
return s;
}


Why it always try to call PyString_FromString first?  if char* cp is already in 
the
interned dict, this PyString_FromString call is waster. so I think this API 
should
implement as:

1. check the interned dict
2. if cp is not in the dict, then call PyString_FromString, and insert the new 
string in
the dict
3. else : call Py_INCREF and return.

Is this right?

Kyo.


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


Re: RegEx with multiple occurrences

2006-05-04 Thread Tim Chase
> p = re.compile("(\*\)",re.IGNORECASE | re.DOTALL)
> m = p.search(data)

First, I presume you didn't copy & paste your expression, as 
it looks like you're missing a period before the second 
asterisk.  Otherwise, all you'd get is any number of 
greater-than signs followed by a closing "" tag.

Second, you're likely getting some foobar results because 
you're not using a "real" string of the form

r'(\)'

> The problem is that I'm getting everything from the 1st
> script's start tag to the last script's end tag in one
> group - so it seems like it parses the string from both
> ends therefore removing far more from that data than I
> want. What am I doing wrong?

Looks like you want the non-greedy modifier to the "*" 
described at

http://docs.python.org/lib/re-syntax.html

(searching the page for "greedy" should turn up the 
paragraph on the modifiers)

You likely want something more like:

r']*>.*?'

In the first atom, you're looking for the remainder of the 
script tag (as much stuff that isn't a ">" as possible). 
Then you close the tag with the ">", and then take as little 
as possible (".*?") of anything until you find the closing 
"" tag.

HTH,

-tkc




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


__getattr__ for global namespace?

2006-05-04 Thread Harold Fellermann
Hi,

I am writing an application that initializes the global namespace, and
afterwards, leaves the user with the python prompt. Now, I want to
catch NameErrors in user input like e.g.

>>> some_name
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'some_name' is not defined

For classes, there are the __getattr__ and __getattribute__ functions.
I wonder if there is some related function for (failed) global
attribute
lookup that is invoked with name as its argument instead.

I consulted the docs, but could not find anything. Any ideas?

- harold -

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


Re: about the implement of the PyString_InternFromString

2006-05-04 Thread Heiko Wundram
Am Donnerstag 04 Mai 2006 13:44 schrieb Kyo Guan:
> Hi guys:
>
>   I have a question about the this API.
>
> PyObject *
> PyString_InternFromString(const char *cp)
> {
>   PyObject *s = PyString_FromString(cp);
>   if (s == NULL)
>   return NULL;
>   PyString_InternInPlace(&s);
>   return s;
> }
>
>
> Why it always try to call PyString_FromString first?  if char* cp is
> already in the interned dict, this PyString_FromString call is waster. so I
> think this API should implement as:

Have you looked at the type of cp? It's const char*, that's not a Python type. 
PyString_FromString does nothing else than create a Python string-object from 
the C string, which can then in turn be interned. This call is necessary.

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


Re: Swaying A Coder Away From Python

2006-05-04 Thread Tim Williams
>   (and why do you
> seem to think that this matters, btw ?)

I actually think it is complete twaddle,  for the same reasons as you.

 It was forwarded to me by someone who knows I use Python, and I
thought it might be of interest to a balanced list,   especially as it
shows an external perspective of Python.   Are we not allowed to post
negative things about Python anymore or did I miss the point ??
-- 
http://mail.python.org/mailman/listinfo/python-list


Python function returns:

2006-05-04 Thread Michael Yanowitz
  I am still new to Python but have used it for the last 2+ months.
One thing I'm still not used to is that functions parameters can't
change as expected. For example in C, I can have
 status = get_network_info (strIpAddress, &strHostname, &nPortNumber)
  where this fictitious function returns a status, but also returns modified
values for a hostname and a port number.
  In Python, there does not seem to be an easy way to have functions return
multiple values except it can return a list such as:
strHostname, nPortNumber, status = get_network_info (strIpAddress,
strHostname,
 nPortNumber)
  Am I missing something obvious? Is there a better, or more standard way
to return values from functions?

Thanks in advance:
Michael Yanowitz


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


Re: Mod_python.publisher behavior - sending .py file tobrowser not processing it in pyton

2006-05-04 Thread Daniel Nogradi
> > As Graham pointed out SetHandler and AddHandler should not be used at
> > the same time. "SetHandler mod_python" causes all files to be served
> > by mod_python and when you refer to them in your browser you don't
> > need to specify any extension such as .py and "AddHandler mod_python
> > .py" causes all files ending in .py to be served by mod_python but in
> > this case when referring to a file in your browser you should add the
> > .py extension. So if you have
> >
> > 
> >SetHandler mod_python
> >PythonHandler mod_python.publisher
> > 
> >
> > and you have a file /whatever/foo.py with a function bar( ) then in
> > your browser you would type http://yourserver/whatever/foo/bar,
>
> When using SetHandler you should still be able to use:
>
>http://yourserver/whatever/foo.py/bar
>
> Your mileage may vary though depending on how some of the
> other bits of Apache configuration are set. See some of previous
> rants for possibly useful about this.
>
>http://www.modpython.org/pipermail/mod_python/2005-August/018828.html
>http://www.modpython.org/pipermail/mod_python/2005-August/018829.html
>http://www.modpython.org/pipermail/mod_python/2006-March/020501.html
>
> > whereas with
> >
> > 
> >AddHandler mod_python .py
> >PythonHandler mod_python.publisher
> > 
> >
> > you would need http://yourserver/whatever/foo.py/bar
>
> As long as you have content negotiation directives set correctly, you
> don't have to use .py extension when AddHandler is used. See my linked
> rants above for details.
>
> > So it's really up to you which behaviour you like, you want *all*
> > files to be served by mod_python or only those that have a specific
> > extension and then you set either AddHandler or SetHandler. But not
> > both :) And in any case, you certainly don't want your .pyc files to
> > be served at all, so you should probably remove "AddHandler mod_python
> > .pyc".
>
> If using AddHandler and Apache has write permission to directory, it is
> actually a good idea to have:
>
>
>deny from all
>
>
> This will prevent the pyc files being accessible.
>
> Using AddHandler for pyc extension will probably actually cause it to
> execute the file as publisher, just like if py extension was used.
> This is
> because mod_python.publisher will quite happily drop the pyc extension
> and use basename to match to .py file.
>
> Besides the fact that AddHandler allows you to mix other file types in
> the same directory, the main difference between SetHandler and
> AddHandler
> as far as mod_python.publisher goes is that when SetHandler is used a
> request against the directory is passed through direct to
> mod_python.publisher
> and it resolves request to index.py.
>
> When AddHandler is used, a request against the directory results in
> mod_dir
> trying to match for a file listed in DirectoryIndex directive. In
> order for
> mod_python.publisher to be triggered, you would need to list index.py
> in the DirectoryIndex directive.
>
> Other than that, with the correct Apache directives defined related
> to content
> negotiation, both ways should allow for optional use of extension.


Thanks for these clarifications, I indeed didn't realize that my rule
of thumb 'AddHandler: extension needed' vs. 'SetHandler: no extension'
is not quite true. Probably my particular configuration gave me the
feeling that it is always the case, but good to know that it isn't :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pleac

2006-05-04 Thread jonas
Thanks Fredrik,

i'm going to buy the book.

After all, there's nothing about the Python language power!

thank you.

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


Re: RegEx with multiple occurrences

2006-05-04 Thread Mike
Tim - you're a legend. Thanks.

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


Re: RegEx with multiple occurrences

2006-05-04 Thread Tim Chase
> Tim - you're a legend. Thanks.

A leg-end?  I always knew something was a-foot.  Sorry to 
make myself the butt of such joking. :)

My pleasure...glad it seems to be working for you.

-tkc (not much of a legend at all...just a regexp wonk)






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


Re: Pythoncard question

2006-05-04 Thread bryan rasmussen
Hi, I'm doing a sort of symbolic linking app in Windows for my own
enjoyment, and figured I would do it in python for the same reason +
learning the language.

The following functions could obviously do with some refactoring. One
obvious thing would be to make wordsetter and wordsforfolder more
generic, and just pass a few extra parameters. But that seems sort of
stupid.

Any suggestions on refactoring here? other improvements?


def getwordslist(word):
  thisword = wordpath + word + ".xml"
  if exists(thisword):
doc =  xml.dom.minidom.parse(thisword)
loc =  doc.childNodes[0]
for i in range(0, len(loc.childNodes)):
  if (loc.childNodes[i].firstChild.data == thispath):
break
  else:
wordsetter(thisword,doc,loc)


  else :
doc = xml.dom.minidom.Document()
loc = doc.createElementNS("", "locations")
doc.appendChild(loc)
wordsetter(thisword,doc,loc)

  return None

def getfolderwords(word):

  if exists(normpath(folderwords)):
doc =  xml.dom.minidom.parse(folderwords)
loc =  doc.childNodes[0]
wordsforfolder(word,doc,loc)


  else :

doc = xml.dom.minidom.Document()
loc = doc.createElementNS("", "wordlist")
doc.appendChild(loc)
xml.dom.ext.PrettyPrint(doc, open(normpath(folderwords), "w"))
wordsforfolder(word,doc,loc)

  return None


def wordsetter(word,doc,loc):
thisloc = doc.createElementNS("", "location")
xexpr= "//location[.='" + thispath + "']"

xp = Evaluate(xexpr,doc.documentElement)
if len(xp) < 1:

loc.appendChild(thisloc)
text = doc.createTextNode(thispath)
thisloc.appendChild(text)
fi = open(word, "w")
fi.write(doc.toxml())


def wordsforfolder(word,doc,loc):
thisloc = doc.createElementNS("", "word")
xexpr= "//word[.='" + word + "']"

xp = Evaluate(xexpr,doc.documentElement)
if len(xp) < 1:

loc.appendChild(thisloc)
text = doc.createTextNode(word)
thisloc.appendChild(text)
fi = open(folderwords, "w")
fi.write(doc.toxml())


Cheers,
Bryan Rasmussen
-- 
http://mail.python.org/mailman/listinfo/python-list


refactoring question

2006-05-04 Thread bryan rasmussen
Hi, I'm doing a sort of symbolic linking app in Windows for my own
enjoyment, and figured I would do it in python for the same reason +
learning the language.

The following functions could obviously do with some refactoring. One
obvious thing would be to make wordsetter and wordsforfolder more
generic, and just pass a few extra parameters. But that seems sort of
stupid.

Any suggestions on refactoring here? other improvements?


def getwordslist(word):
 thisword = wordpath + word + ".xml"
 if exists(thisword):
   doc =  xml.dom.minidom.parse(thisword)
   loc =  doc.childNodes[0]
   for i in range(0, len(loc.childNodes)):
 if (loc.childNodes[i].firstChild.data == thispath):
   break
 else:
   wordsetter(thisword,doc,loc)


 else :
   doc = xml.dom.minidom.Document()
   loc = doc.createElementNS("", "locations")
   doc.appendChild(loc)
   wordsetter(thisword,doc,loc)

 return None

def getfolderwords(word):

 if exists(normpath(folderwords)):
   doc =  xml.dom.minidom.parse(folderwords)
   loc =  doc.childNodes[0]
   wordsforfolder(word,doc,loc)


 else :

   doc = xml.dom.minidom.Document()
   loc = doc.createElementNS("", "wordlist")
   doc.appendChild(loc)
   xml.dom.ext.PrettyPrint(doc, open(normpath(folderwords), "w"))
   wordsforfolder(word,doc,loc)

 return None


def wordsetter(word,doc,loc):
   thisloc = doc.createElementNS("", "location")
   xexpr= "//location[.='" + thispath + "']"

   xp = Evaluate(xexpr,doc.documentElement)
   if len(xp) < 1:

   loc.appendChild(thisloc)
   text = doc.createTextNode(thispath)
   thisloc.appendChild(text)
   fi = open(word, "w")
   fi.write(doc.toxml())


def wordsforfolder(word,doc,loc):
   thisloc = doc.createElementNS("", "word")
   xexpr= "//word[.='" + word + "']"

   xp = Evaluate(xexpr,doc.documentElement)
   if len(xp) < 1:

   loc.appendChild(thisloc)
   text = doc.createTextNode(word)
   thisloc.appendChild(text)
   fi = open(folderwords, "w")
   fi.write(doc.toxml())


Cheers,

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


Re: Pythoncard question

2006-05-04 Thread bryan rasmussen
oops, sorry about that. I copied the message over in gmail but forgot
to change the subject.


Sorry,
Bryan Rasmussen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem building extension under Cygwin (ImportError: Bad address)

2006-05-04 Thread Jason Tishler
Lars,

On Thu, May 04, 2006 at 03:50:13AM -0700, Lars wrote:
> I have problems building a simple handcoded C-extension (hello.c) with
> Cygwin and gcc3.4.4. I hope somebody has encountered the same problem
> before, and has some advice.
> 
> [snip]

The following works for me:

$ gcc -shared -I/usr/include/python2.4 -o hello.dll hello.c 
-L/usr/lib/python2.4/config -lpython2.4
$ python -c'import hello;q = hello.message("Lars");print q'
Hello, Lars
$ python hellouse.py
Hello, C
Hello, module /tmp/Examples/PP2E/Integrate/Extend/Hello/hello.dll
Hello, 0
Hello, 1
Hello, 2

Note I had to apply the attached patch to get hello.c to compile.

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
--- hello.c.orig2006-05-04 08:06:06.769910400 -0400
+++ hello.c 2006-05-04 08:06:10.988633400 -0400
@@ -25,7 +25,7 @@
 {"message", message, 1},   /* method name, C func ptr, always-tuple */
 {NULL, NULL}   /* end of table marker */
 };
-,
+
 /* module initializer */
 void inithello()   /* called on first import */
 {  /* name matters if loaded dynamically */
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Swaying A Coder Away From Python

2006-05-04 Thread Fredrik Lundh
Tim Williams wrote:

> It was forwarded to me by someone who knows I use Python, and I
> thought it might be of interest to a balanced list,   especially as it
> shows an external perspective of Python.   Are we not allowed to post
> negative things about Python anymore /.../

nope, but if we were to post to the list every time some random blogger says
something about Python, we wouldn't have room for much other stuff.

(and it doesn't show an external perspective of Python; it's a piece of lousy 
re-
porting that treats some random guy as an authority, at a moment in time where
the *real* story out there is that light-weight community-developed languages
are beginning to seriously invade the spaces formerly occupied by monolithic
environments controlled by Sun and Microsoft.  there are lots of stuff going on
out there these days...)

 



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


Re: Because of multithreading semantics, this is not reliable.

2006-05-04 Thread Olaf Meding
> return result   before that line, some other thread added a value !

Sure, but that is the nature of using threads and a mutex.  I hope you are
you not saying that every function that uses a mutex should have a comment
saying this is not "reliable"?

Olaf


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


Re: Swaying A Coder Away From Python

2006-05-04 Thread BartlebyScrivener
I'm picking this up via clp on Google Groups. I can't tell what Mr.
Lundh is referring to. The first line of his post is: "Tim Williams
wrote" but there's nothing that comes before. I had seen the article on
Django on Digg I think, but what is article Tim Williams is referring
to?

Thanks,

rick

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


HTMLParseError: EOF in middle of construct error

2006-05-04 Thread Mike
Me again.

I'm getting this error when parsing an external URL - I understand that
a common cause of this is badly formed HTML (or XHTML) and that's fair
enough, but is there any way to turn the parser into forgiving mode?

As I'm getting this error from documents over which I have no control,
I need to be able to recover from this situation. Is there a way to
clean the document before parsing it, or have the parser ignore the
issue and proceed (which would probably be ok in my case)?

Mike

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


Re: about the implement of the PyString_InternFromString

2006-05-04 Thread Fredrik Lundh
Kyo Guan wrote:

> I have a question about the this API.
>
> PyObject *
> PyString_InternFromString(const char *cp)
> {
> PyObject *s = PyString_FromString(cp);
> if (s == NULL)
> return NULL;
> PyString_InternInPlace(&s);
> return s;
> }
>
>
> Why it always try to call PyString_FromString first?  if char* cp is already 
> in the
> interned dict, this PyString_FromString call is waster. so I think this API 
> should
> implement as:
>
> 1. check the interned dict
> 2. if cp is not in the dict, then call PyString_FromString, and insert the 
> new string in
> the dict
> 3. else : call Py_INCREF and return.
>
> Is this right?

Python dictionaries contains Python objects, not C strings, and it's a bit 
difficult
to look for an object if you don't have it.

 



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


Re: HTMLParseError: EOF in middle of construct error

2006-05-04 Thread Diez B. Roggisch
Mike wrote:

> Me again.
> 
> I'm getting this error when parsing an external URL - I understand that
> a common cause of this is badly formed HTML (or XHTML) and that's fair
> enough, but is there any way to turn the parser into forgiving mode?
> 
> As I'm getting this error from documents over which I have no control,
> I need to be able to recover from this situation. Is there a way to
> clean the document before parsing it, or have the parser ignore the
> issue and proceed (which would probably be ok in my case)?

google:BeatifulSoup

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


Re: Python function returns:

2006-05-04 Thread Diez B. Roggisch
Michael Yanowitz wrote:

>   I am still new to Python but have used it for the last 2+ months.
> One thing I'm still not used to is that functions parameters can't
> change as expected. For example in C, I can have
>  status = get_network_info (strIpAddress, &strHostname, &nPortNumber)
>   where this fictitious function returns a status, but also returns
>   modified
> values for a hostname and a port number.
>   In Python, there does not seem to be an easy way to have functions
>   return
> multiple values except it can return a list such as:
> strHostname, nPortNumber, status = get_network_info (strIpAddress,
> strHostname,
>  nPortNumber)
>   Am I missing something obvious? Is there a better, or more standard way
> to return values from functions?

No, that exactly is the way to go. But usually one uses tuples and the
possibility of sequence-unpacking together to reach a solution tha at least
to my eye looks more favorable:


def foo(a, b):
return a*b, a+c

a = 10
b = 20

a, b = foo(a, b)


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


Multiple Version Install?

2006-05-04 Thread David C.Ullrich
Would there be issues (registry settings, environment
variables, whatever) if a person tried to install
versions 1.x and 2.x simultaneously on one Windows
system? Windows 98, if it matters.

(I can handle the file associations with no problem.)

Thanks.

**

If anyone feels like pointing out that there's simply
no reason to want to keep 1.x after installing the
current version: By all means talk me into that!

The problem is not that I'm concerned about backwards
compatibility of Python code. The problem is that I
use Python embedded in various Delphi programs,
including a "DIDE" that I use really a lot, via
a certain set of Delphi "components". These components
don't seem to work with 2.x. Presumably the PyDelphi
people have new versions of the components that do
work with Python 2.x. These presumably use much
newer versions of Delphi than what I have. A new
version of Delphi is not free... If I could use
Python 2.x when I need to while continuing to
use 1.x the way I have been for things that 
don't need 2.x that would be convenient.



David C. Ullrich
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python function returns:

2006-05-04 Thread Duncan Booth
Michael Yanowitz wrote:

>   In Python, there does not seem to be an easy way to have functions
>   return 
> multiple values except it can return a list such as:
> strHostname, nPortNumber, status = get_network_info (strIpAddress,
> strHostname,
>  nPortNumber)
>   Am I missing something obvious? Is there a better, or more standard
>   way 
> to return values from functions?

The only obvious thing you are missing is that you don't pass in values 
which are only results. Duplicating the parameters and results as you have 
above would be unlikely to happen very much in practice.

Oh, and it doesn't return a list, it actually returns a tuple but it is 
easiest just to think of your function as just returning three results.

Returning additional results is better than rebinding parameters because it 
makes it really clear at the point of calling which variables are 
parameters and which are results.

The other not very pythonic thing about your example is that it returns a 
status code: Python largely tends towards using exceptions rather than 
status codes, so if in C you had:

 switch ((status=get_network_info(addr, &host, &port)) {
 case S_OK:
break;
 case ERROR_1:
... handle error ...
break;
 case default:
... handle other errors ...
 };

In Python you would have something like:

   try:
  host, port = get_network_info(addr)
   except ERROR_1:
  ... handle error ...
   except:
  ... handle other errors ...

which means you can handle the error either right next to the call or at 
some outer level (you don't have to manually propogate your status), you 
can't accidentally forget to check the status code, and the actual call is 
much simpler and clearer (especially if the error is handled at some outer 
level).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Gettings subdirectories

2006-05-04 Thread Philippe Martin
Hi,

The second edition of "Programming Python - O'REILLY - Mark Lutz" shows how
to do that using "os.path.walk"

Philippe





Florian Lindner wrote:

> Hello,
> how can I get all subdirectories of a given directories? os.listdir()
> gives me all entries and I've found no way to tell if an object is a file
> or a directory.
> 
> Thanks,
> 
> Florian

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


Re: Python function returns:

2006-05-04 Thread Tim Chase
> In Python, there does not seem to be an easy way to have
> functions return multiple values except it can return a
> list such as: strHostname, nPortNumber, status =
> get_network_info (strIpAddress, strHostname, nPortNumber)
>  Am I missing something obvious? Is there a better, or
> more standard way to return values from functions?

This *is* the "better" and "standard" way to do it.  There 
are *worse* ways to emulate C/C++ if you want, but it takes 
being *more* obtruse.  Because certain objects are mutable, 
nothing[*] prevents you from doing something like

x = []
def foo(q):
x.append(42)
foo(x)
print repr(x)

which will return that you've added "42" to your list. 
However, it's ugly and relies on side effects.

They Python way (that you deride) is much clearer.  Your 
input goes in the parameters, and your output gets assigned 
the way functions are intended to work.  Unambiguous.

I don't expect to call a sine function, and get the result 
in the parameter; rather I expect to get it as the result of 
the function.  Okay...unless I'm working in Assembly 
language (but that's one of many reasons *why* I choose 
Python ;)

Just a few thoughts,

-tkc
[*] nothing other than being given dirty looks by folks 
reading your code...






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


Re: Because of multithreading semantics, this is not reliable.

2006-05-04 Thread Sergei Organov
"Olaf Meding" <[EMAIL PROTECTED]> writes:

>> return result   before that line, some other thread added a value !
>
> Sure, but that is the nature of using threads and a mutex.  I hope you are
> you not saying that every function that uses a mutex should have a comment
> saying this is not "reliable"?

Strictly speaking, mutex has nothing to do about it, -- if there were no
mutex there the problem would have been even worse, so this is the
nature of accessing shared resources by multiple threads.

Somewhat similar example is accessing a file after checking for its
existence in a multi-tasking OS:

if fileExists(fileName):
openFile(fileName)

has the same problem, -- at open_file time one can't rely on existence
of the file, so the check for existence is useless.

-- 
Sergei.

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


Subclassing array

2006-05-04 Thread TG
Hi.

i've already something about inheriting from array a few weeks ago and
had my answer. But again, there is something that I don't understand.
Here is my vector class, which works quite well :

class Vector(array):
def __new__(cls,length,data=None):
return super(Vector,cls).__new__(cls,'f')

def __init__(self,length,data=None):
if data == None:
for _ in xrange(length):
self.append(0.0)
else:
for i in xrange(length):
self.append(data[i])



Now, i want to inherit from this vector class :

class Stimulus(Vector):
def __init__(self,width,height,label,data=None):
Vector.__init__(self,width*height,data)
self.width = width
self.height = height
self.label = label

This doesn't seem to work :
>>> s = Stimulus(10,10,"data")
TypeError: __new__() takes at most 3 arguments (4 given)

In order to make it work, it seems that I have to redefine __new__
again, like this.

def __new__(cls,width,height,label,data=None):
return super(Stimulus,cls).__new__(cls,width*height)

Why is that ?
When I call Vector.__init__() in Stimulus, doesn't it also call __new__
? I don't understand the detail of callings to __new__ and __init__ in
python inheritance ...

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


Python sample code for PLSQL REF CURSORS

2006-05-04 Thread A.M
Hi,



I am having hard time to find a sample that shows me how to return an OUT 
REF CURSOR from my oracle stored procedure to my python program.



The technique is explained here for Java and Visual Basic:

http://www.oracle-base.com/articles/8i/UsingRefCursorsToReturnRecordsets.php



I am looking for similar code for Python



Any help would be appreciated,

Alan


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


Re: This coding style bad practise?

2006-05-04 Thread Martin P. Hellwig


Thanks for the input folks!
I adapted my script to the given suggestions and it's now far more 
'logical', for reference I added it below.

-- 
mph

- script -
> import string
> import time
> 
> class IDGenerator(object):
> """(leading_id, subversion_length, tz) # tz = 'local' or 'gm' (default)
> Create an ID from a given string, a current datetimestamp and version
> number which wraps around at given subversion_length.
> 
> Example usage:
> >>> id = IDGenerator('01',2)
> >>> id()
> '01_20060504_112304_1'
> >>> id()
> '01_20060504_112306_2'
> >>> id()
> '01_20060504_112307_1'
> >>> 
> >>> id = IDGenerator(0005,99) # Note that an int will be cast to a string!
> >>> id()
> '5_20060504_112324_01'
> >>> id()
> '5_20060504_112327_02'
> >>> id
>  previous ID is 5_20060504_112324_01 and
> current ID is 5_20060504_112327_02
> >>> 
> 
> """
> 
> def __init__(self,leading_id, subversion_length, timezone='gm'):
> self.id = str(leading_id)
> self.length = int(subversion_length)
> fill_length = len(str(self.length))
> self.current = None
> self.previous = None
> 
> def fill(number):
> return(string.zfill(number,fill_length))
> self.fill = fill
> 
> if timezone == 'local':
> self.timeset = time.localtime
> else:
> self.timeset = time.gmtime
> 
> 
> def __call__(self):
> # If the subversion length has been reached or the generator has not
> # been defined, (re)define it, otherwise return the next value of the
> # subversion.
> try:
> return_value = self.range_gen.next()
> 
> except:
> self.range_gen = ( number for number in range(1,self.length+1) )
> return_value = self.range_gen.next()
> 
> # Create the version stamp.
> return_value = self.id +\
>time.strftime("_%Y%m%d_%H%M%S_",self.timeset())+\
>self.fill(return_value)
> 
> # Copy the current ID to the previous and assign a new one to current.
> self.previous = self.current
> self.current = return_value
> 
> # And return it.
> return(self.current)
> 
> def __repr__(self):
> return(str(self.__class__) +
>' previous ID is ' +
>str(self.previous) +
>' and current ID is ' +
>str(self.current))
- script -
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python function returns:

2006-05-04 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Tim Chase <[EMAIL PROTECTED]> wrote:

> They Python way (that you deride) is much clearer.  Your 
> input goes in the parameters, and your output gets assigned 
> the way functions are intended to work.  Unambiguous.

It's probably worth mentioning that the only reason C/C++ uses pointer 
arguments to return multiple values is because in the early versions of C, 
a function could not return a struct, so passing in pointers was the only 
way to return multiple values.

Don't turn something which was forced upon us by a historical compiler 
limitation into something you want to emulate in other langauges which have 
better solutions to the problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Swaying A Coder Away From Python

2006-05-04 Thread Tim Williams
On 04/05/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> nope, but if we were to post to the list every time some random blogger says
> something about Python, we wouldn't have room for much other stuff.
>

It wasn't from a random blogger,  it was from an email newsletter for
this site:

http://www.devwebpro.co.uk/

I am not a member or in anyway related to the site  :) and have no
idea how large its user-base is.   As I said,  the email was forwarded
to someone who thought I would be interested.

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


Shed Skin Python-to-C++ Compiler - Summer of Code?

2006-05-04 Thread Mark Dufour
Hello all,

As Bearophile pointed out, I have just released Shed Skin 0.0.8. For
those of you that do not know Shed Skin, it is an optimizing
Python-to-C++ compiler, that allows for translation of pure
(unmodified) Python programs into optimized machine language. The
speed of generated code is typically 2-40 times, 12 on average, faster
than when using Psyco, and 2-220 times, 45 on average, than when using
CPython, for a sizeable set of benchmarks (such as a raytracer, chess
player, othello player, neural network sim, sat solver, several sudoku
solvers..) See http://mark.dufour.googlepages.com for a more detailed
introduction to Shed Skin, its current limitations, and a link to my
Master's Thesis, which contains more precise results and an
explanation of how the compiler works.

Now that I have released a fairly clean and stable (but still very
much alpha!) version of my compiler, I would like to invite other
people to join the project. Seeing that the SoC application deadline
for this year is only in about a week (:P), this would be a nice way
to help out and get started in SS development. Note that I did a SoC
project on SS last year, which has improved it tremendously.

Two important aspects that still need to be investigated are memory
optimizations (e.g. transforming heap allocation into stack- and
static preallocation), more efficient string support (rather than
using the inefficient C++ STL string type) and looking at integration
with the standard library and calling compiled code from Python. Note
that especially memory optimizations would also be an interesting
Master's Thesis topic. Again, see http://mark.dufour.googlepages.com
for more details about possible ways to help out. Please let me know
if you are even remotely interested :-)

Otherwise, a simple way to also help out, is to send me bug reports of
small code fragments that SS does not compile correctly, or you can
just send me complete programs. Bug reports are always motivating,
make my work more time-efficient, and are the best way to getting your
own programs supported.


Thanks.
Mark.
--
"How should I know if it works? That's what beta testers are for. I
only coded it." - Linus Torvalds
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python function returns:

2006-05-04 Thread bruno at modulix
Michael Yanowitz wrote:
>   I am still new to Python but have used it for the last 2+ months.
> One thing I'm still not used to is that functions parameters can't
> change as expected. 
>
> For example in C, I can have
>  status = get_network_info (strIpAddress, &strHostname, &nPortNumber)

You have to understand that Python and C are totally different beasts.

A C variable is mostly symbolic name for a memory address, tagged with
type infos. Assigning to a variable means storing a value at this
address. Reading a variable means retrieving whatever value is stored at
this memory address.

Python does not in fact have a concept of "variables". It has names and
objects. A binding is the association (in a hash table) of a symbolic
name (which is nothing more than a name) and a reference (read:
something like a smart pointer) to an object (which is itself a complex
data structure). So-called "assignement" (correct term is "binding")
'binds' together a name and a reference to an object. Except for some
special cases (mainly objects - which are they're own namespaces - and
when using the 'global' statement), this creates an entry in the current
namespace. Also, rebinding a name has no effect on other names bound to
the same object.

Function's params are bindings in the function's local namespace. This
means that the params *names* are local to the function. So rebinding a
param in a function won't have no effect on bindings in the caller's
namespace.

*But* - since many names can refer to the same object - *modifying* the
object referenced by a name will, well, modify this object, so this
modification will be visible everywhere.

ie (dummy example):

def appendToList(alist, what):
  alist.append(what)

mylist = []
appendToList(mylist, 42)
print mylist

What doesn't work as you'd expect is:

def failsToHaveSideEffects(alist, anything):
  print "before rebinding : alist = ", alist, " - anything = ", anything
  alist = anything
  print "after rebinding: alist = ", alist

mylist = []
print "before function call, mylist = ", mylist
failsToHaveSideEffects(mylist, 42)
print "after function call, mylist = ", mylist


So as you can see, it's quite possible for a function to *modify* it's
params - it's just rebindings of params that won't have side effects
outside the function's namespace.

Now, there is the case of immutable types (int, strings, tuples, ).
As implied, one cannot modify objects of these types - just create them.
So in order to have a function that "change the value" of an immutable
object, you have to wrap it into a mutable object, ie:

def getAnswer(alist):
  alist[0] = "42"

answer = ["answer is ?"]
getAnswer(answer)
print "answer is : ", answer[0]

(snip)

>   In Python, there does not seem to be an easy way to have functions return
> multiple values except it can return a list such as:
> strHostname, nPortNumber, status = get_network_info (strIpAddress,
> strHostname,
>  nPortNumber)
>   Am I missing something obvious? Is there a better, or more standard way
> to return values from functions?

This *is* the 'standard' (ie: idiomatic) way to return multiple values
from a function. The C idiom of passing pointers to variables that are
to be modified comes from C's limitations, namely no exception handling
and only one return value[1], which leads to using the return value as a
status report and relying on side effect for useful values.



[1] To be pedantic, Python only allows one return value too - but this
value can be a tuple or list, and then one can take advantage of
tuple/list expansions that allows multiple assignment...

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Swaying A Coder Away From Python

2006-05-04 Thread bruno at modulix
BartlebyScrivener wrote:
> I'm picking this up via clp on Google Groups. I can't tell what Mr.
> Lundh is referring to. The first line of his post is: "Tim Williams
> wrote" but there's nothing that comes before. I had seen the article on
> Django on Digg I think, but what is article Tim Williams is referring
> to?

Google for "David A. Utter"

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem building extension under Cygwin (ImportError: Bad address)

2006-05-04 Thread Lars
Thanks Jason, it works now.

There seems to be some sort of issue with ld in cygwin when compiling
shared libraries (e.g. DLL's).
This worked on my Cygwin installation also:

--
gcc hello.c -I/usr/include/python2.4/ -L/usr/lib/python2.4/config/
-lpython2.4 -shared -o hello.dll
python hellouse.py
(gives the right answer)


But first compiling hello.c with gcc, then linking it with gnu-ld just
won't work. I only really need to compile one C-file to a shared
library so it doesn't matter so much for me. But bigger projects will
have a problem..

--
gcc -c hello.c -I/usr/include/python2.4/
ld -shared hello.o -o hello.so -L /usr/lib/python2.4/config -lpython2.4
-lc
python hellouse.py
Traceback (most recent call last):
  File "hellouse.py", line 1, in ?
import hello
ImportError: Bad address
---

-Lars

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


Re: Because of multithreading semantics, this is not reliable.

2006-05-04 Thread Christophe
Olaf Meding a écrit :
>>return result   before that line, some other thread added a value !
> 
> 
> Sure, but that is the nature of using threads and a mutex.  I hope you are
> you not saying that every function that uses a mutex should have a comment
> saying this is not "reliable"?

That function can return a value that was already obsolete even before 
it finished executing. And so special care should be taken by the user 
so that he can either cope with that or make sure that it doesn't happens.

As was said, it's the same reason the user should not do a if 
fileExists() followed by a openFile. Same reason that there is a warning 
in the "os.access" manual
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Swaying A Coder Away From Python

2006-05-04 Thread Tim Williams
On 4 May 2006 05:24:40 -0700, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
> I'm picking this up via clp on Google Groups. I can't tell what Mr.
> Lundh is referring to. The first line of his post is: "Tim Williams
> wrote" but there's nothing that comes before. I had seen the article on
> Django on Digg I think, but what is article Tim Williams is referring
> to?
>
> Thanks,
>
> rick

Rick,

I found the web version at.

http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html

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


Re: unable to resize mmap object

2006-05-04 Thread Georg Brandl
Carl Banks wrote:

> Frankly, I'm not so sure matching Windows behavior is a great idea.
> mmap module seems to be having an identity crisis.  Is it a low-level
> system call, or a high-level, OS-independent way to access files as
> blocks of memory?  The modules is moving towards the latter (what with
> Unix mmap accepting ACCESS-style flags, and now this file-resizing
> behavior).  I actually favor a two-level approach similar to file I/O:
> there would low-level system calls in the os module, and high-level
> mmap object.  (The high-level object would go all the way.  It would
> accept a filename rather than a file descriptor, anonymous blocks would
> be handled OS-independently, rather than mapping /dev/zero, and so on.)

I'm sure that we will gladly accept a patch implementing this approach.

Cheers,
Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Because of multithreading semantics, this is not reliable.

2006-05-04 Thread Grant Edwards
On 2006-05-04, Olaf Meding <[EMAIL PROTECTED]> wrote:

>> return result   before that line, some other thread added a value !
>
> Sure, but that is the nature of using threads and a mutex.

Yes.

> I hope you are you not saying that every function that uses a
> mutex should have a comment saying this is not "reliable"?

My point exactly.

-- 
Grant Edwards   grante Yow!  My pants just went to
  at   high school in the Carlsbad
   visi.comCaverns!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Gettings subdirectories

2006-05-04 Thread Lou Losee
import os.pathos.path.isdir(file)LouOn 5/4/06, Philippe Martin <[EMAIL PROTECTED]> wrote:
Hi,The second edition of "Programming Python - O'REILLY - Mark Lutz" shows how
to do that using "os.path.walk"PhilippeFlorian Lindner wrote:> Hello,> how can I get all subdirectories of a given directories? os.listdir()> gives me all entries and I've found no way to tell if an object is a file
> or a directory.>> Thanks,>> Florian--http://mail.python.org/mailman/listinfo/python-list
-- Artificial Intelligence is no match for Natural Stupidity
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python sample code for PLSQL REF CURSORS

2006-05-04 Thread Gerhard Häring
A.M wrote:
> Hi,
> 
> I am having hard time to find a sample that shows me how to return an OUT 
> REF CURSOR from my oracle stored procedure to my python program. [...]

import cx_Oracle

con = cx_Oracle.connect("me/[EMAIL PROTECTED]")
cur = con.cursor()
outcur = con.cursor()
cur.execute("""
 BEGIN
 MyPkg.MyProc(:cur);
 END;""", cur=outcur)

for row in out_cur:
 print row

HTH,

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


Re: Because of multithreading semantics, this is not reliable.

2006-05-04 Thread OlafMeding
Christophe

> Same reason that there is a warning in the "os.access" manual

I understand the if file exists open it code.

I looked at the os.access documentation and see no "warning" or "not
reliable" wording there.
  6.1.4 Files and Directories
  access(path, mode)


Olaf

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


Re: pleac

2006-05-04 Thread Thomas Guettler
Am Thu, 04 May 2006 04:05:49 -0700 schrieb jonas:

> Hi,
> 
> I'm new to python.
> After a search on
> http://pleac.sourceforge.net/pleac_python/index.html
> why python have a low %?

Python has the highest percentage of all languages at pleac.

For those who don't know pleac:

"""Following the great Perl Cookbook (by Tom Christiansen & Nathan
Torkington, published by O'Reilly; you can freely browse an excerpt of the
book here) which presents a suite of common programming problems solved in
the Perl language, this project aims to gather fans of programming, in
order to implement the solutions in other programming languages.

If successful, this project may become a primary resource for quick, handy
and free reference to solve most common programming problems using
higher-level programming languages, and for comparison on ease-of-use and
power/efficiency of these languages.
"""

-- 
Thomas Güttler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

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


Re: Multiple Version Install?

2006-05-04 Thread Fredrik Lundh
David C.Ullrich wrote:

> Would there be issues (registry settings, environment
> variables, whatever) if a person tried to install
> versions 1.x and 2.x simultaneously on one Windows
> system? Windows 98, if it matters.
>
> (I can handle the file associations with no problem.)

in general, no.

(I usually have about a dozen Python's, or more, on most of my
windows boxes)

however, applications that look in the registry may only find the
last one you've installed.

 



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


Re: Sorting a list of dictionaries by dictionary key

2006-05-04 Thread Alex Martelli
Tim Chase <[EMAIL PROTECTED]> wrote:

> > assuming that DateTime returns something that compares correctly, you can
> > do something like:
> > 
> > def sortkey(item):
> > return item.get("from_datetime")
> > 
> > data.sort(key=sortkey)
> > 
> > (assuming Python 2.4 or later)
> 
> Building on Fredrik's solution, for 2.3 (or earlier?), you 
> can use
> 
> data.sort(lambda a,b: cmp(a['from_datetime'], 
> b['from_datetime']))

...and get a potentially very slow sort, if the list is long.  Much
faster:

_aux = [ (d['from_datetime'], i, d) for (i, d) in enumerate(data) ]
_aux.sort()
data[:] = [ t[-1] for t in _aux ]


Google Search for DSU or [Decorate Sort Undecorate] ...


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


Re: Because of multithreading semantics, this is not reliable.

2006-05-04 Thread Christophe
[EMAIL PROTECTED] a écrit :
> Christophe
> 
> 
>>Same reason that there is a warning in the "os.access" manual
> 
> 
> I understand the if file exists open it code.
> 
> I looked at the os.access documentation and see no "warning" or "not
> reliable" wording there.
>   6.1.4 Files and Directories
>   access(path, mode)
> 
> 
> Olaf
> 

6.1.4 Files and Directories

access( path, mode)

Use the real uid/gid to test for access to path. Note that most 
operations will use the effective uid/gid, therefore this routine can be 
used in a suid/sgid environment to test if the invoking user has the 
specified access to path. mode should be F_OK to test the existence of 
path, or it can be the inclusive OR of one or more of R_OK, W_OK, and 
X_OK to test permissions. Return True if access is allowed, False if 
not. See the Unix man page access(2) for more information. Availability: 
Macintosh, Unix, Windows.
Note: Using access() to check if a user is authorized to e.g. open a 
file before actually doing so using open() creates a security hole, 
because the user might exploit the short time interval between checking 
and opening the file to manipulate it.



I call that note a warning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-04 Thread Dave Hansen
On Tue, 02 May 2006 18:52:48 GMT in comp.lang.python, John Salerno
<[EMAIL PROTECTED]> wrote:

[...]
>
>Yeah, after trying some crazy things, I just wrote it this way:
>
>def truth_test(seq):
> truth = 0
> for item in seq:
> if item:
> truth += 1
> if truth == 1:
> return True
> else:
> return False

You could replace those last four lines with

  return truth == 1

>
>Not sure I like having to keep a counter though, but the other stuff I 

Well, if you want something minimalist, you could try

   def truth_test(seq):
  return sum(1 for item in seq if item) == 1

Though I'm not sure it's really any clearer...

>did was really convoluted, like checking to see if the first item was 
>True, and if it was, popping it from the list and iterating over the 
>rest of the items (needless to say, the in-place change wasn't helpful).

Perhaps something like

   def truth_test(seq):
  found = False
  for item in seq:
 if item:
if found:
   return False
found = True
  return found

Gets you an early exit, anyway...

All code untested.  Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-04 Thread Paul Rubin
Dave Hansen <[EMAIL PROTECTED]> writes:
> Well, if you want something minimalist, you could try
> 
>def truth_test(seq):
>   return sum(1 for item in seq if item) == 1

def truth_test(seq):
   return sum(map(bool, seq)) == 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling a Postgres Function using CGI written in Python

2006-05-04 Thread Fuzzydave
cheers :)

thats what i wanted to know :)

David

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


Re: python strings

2006-05-04 Thread Sion Arrowsmith
Bryan  <[EMAIL PROTECTED]> wrote:
> >>> s = '\x00'
> >>> s[0] == chr(0)
>True

That's a little excessive when:

>>> s = '\0'
>>> s[0] == chr(0)
True

Oh, and to reassure the OP that that null really is *in* the string:

>>> len(s)
1

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Unicode code has no method float() ?

2006-05-04 Thread Rony Steelandt
How can I get the value of a Unicode object ?

When I do myobject.float() I get the error message that it doesn't have 
a float() attribute

tia

R_

-- 
---
Rony Steelandt
BuCodi
rony dot steelandt (at) bucodi dot com

Visit the python blog at http://360.yahoo.com/bucodi


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


Re: Unicode code has no method float() ?

2006-05-04 Thread Alexandre Fayolle
Le 04-05-2006, Rony <[EMAIL PROTECTED]> nous disait:
> How can I get the value of a Unicode object ?
>
> When I do myobject.float() I get the error message that it doesn't have 
> a float() attribute

Try to use the float builtin function, as in: float(myobject) instead of
a method. 


-- 
Alexandre Fayolle  LOGILAB, Paris (France)
Formations Python, Zope, Plone, Debian:  http://www.logilab.fr/formations
Développement logiciel sur mesure:   http://www.logilab.fr/services
Python et calcul scientifique:   http://www.logilab.fr/science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subclassing array

2006-05-04 Thread Alex Martelli
TG <[EMAIL PROTECTED]> wrote:
   ...
> When I call Vector.__init__() in Stimulus, doesn't it also call __new__
> ? I don't understand the detail of callings to __new__ and __init__ in
> python inheritance ...

Calling a (new-style) class does __new__ first, THEN calls the class's
__init__ on the resulting instance -- and the arguments you're passing
when calling the class go to both __new__ and __init__.


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


Tuple assignment and generators?

2006-05-04 Thread Tim Chase
Just as a pedantic exercise to try and understand Python a 
bit better, I decided to try to make a generator or class 
that would allow me to unpack an arbitrary number of 
calculatible values.  In this case, just zeros (though I 
just to prove whatever ends up working, having a counting 
generator would be nice).  The target syntax would be 
something like

 >>> a,b,c = zeros()
 >>> q,r,s,t,u,v = zeros()

where "zeros()" returns an appropriately sized tuple/list of 
zeros.

I've tried a bit of googling, but all my attempts have just 
ended up pointing to pages that blithly describe tuple 
assignment, not the details of what methods are called on an 
object in the process.

My first thought was to get it to use a generator:

def zeros():
while 1: yield 0

However, I get back a "ValueError: too many values to 
unpack" result.

As a second attempt, I tried a couple of attempts at classes 
(I started with the following example class, only derived 
from "object" rather than "list", but it didn't have any 
better luck):

 >>> class zeros(list):
... def __getitem__(self,i):
... return 0
...
 >>> z = zeros()
 >>> a,b,c = z
Traceback (most recent call last):
   File "", line 1, in ?
ValueError: need more than 0 values to unpack


It looks like I need to have a pre-defined length, but I'm 
having trouble figuring out what sorts of things need to be 
overridden.  It seems like I sorta need a

def __len__(self):
return INFINITY

so it doesn't choke on it.  However, how to dupe the 
interpreter into really believing that the object has the 
desired elements is escaping me.  Alternatively if there was 
a "doYouHaveThisManyElements" pseudo-function that was 
called, I could lie and always return true.

Any hints on what I'm missing?

Thanks,

-tkc








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


Re: stripping unwanted chars from string

2006-05-04 Thread Alex Martelli
Edward Elliott <[EMAIL PROTECTED]> wrote:

> I'm looking for the "best" way to strip a large set of chars from a filename
> string (my definition of best usually means succinct and readable).   I
> only want to allow alphanumeric chars, dashes, and periods.  This is what I
> would write in Perl (bless me father, for I have sinned...):
> 
> $filename =~ tr/\w.-//cd, or equivalently 
> $filename =~ s/[^\w.-]//
> 
> I could just use re.sub like the second example, but that's a bit overkill.
> I'm trying to figure out if there's a good way to do the same thing with
> string methods.  string.translate seems to do what I want, the problem is
> specifying the set of chars to remove.  Obviously hardcoding them all is a
> non-starter.

(untested code, but, the general idea shd be correct)...:

class KeepOnly(object):
allchars = ''.join(chr(i) for i in xrange(256))
identity = string.maketrans('', '')

def __init__(self, chars_to_keep):
self.chars_to_delete = self.allchars.translate(
self.identity, chars_to_keep)

def __call__(self, some_string):
return some_string.translate(self.identity,
self.chars_to_delete)


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


Re: Python function returns:

2006-05-04 Thread Sion Arrowsmith
Michael Yanowitz <[EMAIL PROTECTED]> wrote:
>  In Python, there does not seem to be an easy way to have functions return
>multiple values except it can return a list such as:
>strHostname, nPortNumber, status = get_network_info (strIpAddress,
>strHostname,
> nPortNumber)
>  Am I missing something obvious? Is there a better, or more standard way
>to return values from functions?

I'm kind of repeating what other people have said, but there
isn't a better way. Not just in Python, but in any language.
If your function is returning multiple values, why should you
have to split them into one privileged "return value" plus a
bunch of Out (or InOut) parameters? That's a historical mis-
feature of older languages, and one which more newer languages
would do well to fix.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Multiple Version Install?

2006-05-04 Thread David C.Ullrich
On Thu, 4 May 2006 16:17:57 +0200, "Fredrik Lundh"
<[EMAIL PROTECTED]> wrote:

>David C.Ullrich wrote:
>
>> Would there be issues (registry settings, environment
>> variables, whatever) if a person tried to install
>> versions 1.x and 2.x simultaneously on one Windows
>> system? Windows 98, if it matters.
>>
>> (I can handle the file associations with no problem.)
>
>in general, no.

Excellent. Thanks.

>(I usually have about a dozen Python's, or more, on most of my
>windows boxes)
>
>however, applications that look in the registry may only find the
>last one you've installed.
>
> 
>
>




David C. Ullrich
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode code has no method float() ?

2006-05-04 Thread Rony Steelandt
Works, thank you


> Le 04-05-2006, Rony <[EMAIL PROTECTED]> nous disait:
>> How can I get the value of a Unicode object ?
>> 
>> When I do myobject.float() I get the error message that it doesn't have 
>> a float() attribute
>
> Try to use the float builtin function, as in: float(myobject) instead of
> a method. 


-- 
---
Rony Steelandt
BuCodi
rony dot steelandt (at) bucodi dot com

Visit the python blog at http://360.yahoo.com/bucodi


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


Re: Wake on LAN and Shutdown for Windows and Linux

2006-05-04 Thread diffuser78
Any help is appreciated

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


Re: Swaying A Coder Away From Python

2006-05-04 Thread Sion Arrowsmith
>On 4 May 2006 05:24:40 -0700, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
>> I'm picking this up via clp on Google Groups. I can't tell what Mr.
>> Lundh is referring to. The first line of his post is: "Tim Williams
>> wrote" but there's nothing that comes before.

Similarly, I'm reading this via comp.lang.python and the original
article hasn't shown up at this site.

Tim Williams <[EMAIL PROTECTED]> wrote:
>I found the web version at.
>
>http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html

Wherein we find:

He also listed a few reasons why C# appeals to him over Python or Java: 
* anonymous functions (delegates)
* a python-like yield statement
* a nice type system with generics
* interfaces 
* properties (Yay!!)

So that's two of the five Python has, one explicitly acknowledged,
plus the combination of lambda and functions-as-first-class-objects
is as good as (or better than) "anonymous functions (delegates)".
And then we get onto personal preferences as to how to do type
systems. That's not a great deal with which to sway someone.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

pyuno and oootools with OpenOffice 2.0

2006-05-04 Thread Sells, Fred
I'm using windows xp and OpenOffice 2.0 and doing my first project with
pyuno.

I've got the basics to work,.  An example I googled at
http://blogs.nuxeo.com/sections/aggregators/openoffice_org/blogaggregator_vi
ew?b_start:int=0 imported an ootools module.  When I try to import it, it
does not exist,  

Does anyone know where this exists, or why I cannot import it.  

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subclassing array

2006-05-04 Thread Sion Arrowsmith
Alex Martelli <[EMAIL PROTECTED]> wrote:
>TG <[EMAIL PROTECTED]> wrote:
>> When I call Vector.__init__() in Stimulus, doesn't it also call __new__
>> ? I don't understand the detail of callings to __new__ and __init__ in
>> python inheritance ...
>Calling a (new-style) class does __new__ first, THEN calls the class's
>__init__ on the resulting instance -- and the arguments you're passing
>when calling the class go to both __new__ and __init__.

... so you might want something like:

class Vector(array):
def __new__(cls,*args):
return super(Vector,cls).__new__(cls,'f')

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Swaying A Coder Away From Python

2006-05-04 Thread Rony Steelandt

"One problem is that python tools suck," he wrote. Wallace compared the 
various IDEs and other developer tools available to Microsoft's freely 
available Visual Studio Express and called them "toys."



What s wrong with VI ???  :)

R_

>> On 4 May 2006 05:24:40 -0700, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
>>> I'm picking this up via clp on Google Groups. I can't tell what Mr.
>>> Lundh is referring to. The first line of his post is: "Tim Williams
>>> wrote" but there's nothing that comes before.
>
> Similarly, I'm reading this via comp.lang.python and the original
> article hasn't shown up at this site.
>
> Tim Williams <[EMAIL PROTECTED]> wrote:
>> I found the web version at.
>> 


>> http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html
>
> Wherein we find:
>
> He also listed a few reasons why C# appeals to him over Python or Java: 
> * anonymous functions (delegates)
> * a python-like yield statement
> * a nice type system with generics
> * interfaces 
> * properties (Yay!!)
>
> So that's two of the five Python has, one explicitly acknowledged,
> plus the combination of lambda and functions-as-first-class-objects
> is as good as (or better than) "anonymous functions (delegates)".
> And then we get onto personal preferences as to how to do type
> systems. That's not a great deal with which to sway someone.


-- 
---
Rony Steelandt
BuCodi
rony dot steelandt (at) bucodi dot com

Visit the python blog at http://360.yahoo.com/bucodi


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


Re: Problem building extension under Cygwin (ImportError: Bad address)

2006-05-04 Thread Jason Tishler
On Thu, May 04, 2006 at 06:23:23AM -0700, Lars wrote:
> But first compiling hello.c with gcc, then linking it with gnu-ld just
> won't work. I only really need to compile one C-file to a shared
> library so it doesn't matter so much for me. But bigger projects will
> have a problem..

No, it works if you drive it from gcc:

$ gcc -I/usr/include/python2.4 -c hello.c
$ gcc -shared -o hello.dll hello.o -L/usr/lib/python2.4/config -lpython2.4
$ python hellouse.py 
Hello, C
Hello, module /tmp/examples/PP2E/Integrate/Extend/Hello/hello.dll
Hello, 0
Hello, 1
Hello, 2

BTW, if you use Distutils, then it will just work...

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Progamming python without a keyboard

2006-05-04 Thread Rony Steelandt
http://www.newscientisttech.com/article/dn9066

To nice to be true ?

R_

-- 
---
Rony Steelandt
BuCodi
rony dot steelandt (at) bucodi dot com

Visit the python blog at http://360.yahoo.com/bucodi


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


Calling superclass

2006-05-04 Thread Florian Lindner
Hello,
I try to call the superclass of the ConfigParser object:

class CustomizedConfParser(ConfigParser.SafeConfigParser):
def get(self, section, attribute):
try:
return super(CustomizedConfParser, self).get(section, attribute)
# [...]


but that gives only

return super(CustomizedConfParser, self).get(section, attribute)
TypeError: super() argument 1 must be type, not classobj

I don't really understand the error message.

Thanks,

Florian

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


Re: Tuple assignment and generators?

2006-05-04 Thread Diez B. Roggisch
Tim Chase wrote:

> Just as a pedantic exercise to try and understand Python a
> bit better, I decided to try to make a generator or class
> that would allow me to unpack an arbitrary number of
> calculatible values.  In this case, just zeros (though I
> just to prove whatever ends up working, having a counting
> generator would be nice).  The target syntax would be
> something like



By using this:

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


I came up with a small decorator doing that:

import inspect, dis

def expecting():
"""Return how many values the caller is expecting"""
f = inspect.currentframe()
f = f.f_back.f_back
c = f.f_code
i = f.f_lasti
bytecode = c.co_code
instruction = ord(bytecode[i+3])
if instruction == dis.opmap['UNPACK_SEQUENCE']:
howmany = ord(bytecode[i+4])
return howmany
elif instruction == dis.opmap['POP_TOP']:
return 0
return 1

def variably_unpack(f):
def d(*args, **kwargs):
r = f(*args, **kwargs)
exp = expecting()
if exp < 2:
return exp
return (r.next() for i in xrange(exp))
return d

@variably_unpack
def test():
def gen():
i = 0
while True:
yield i
i += 1
return gen()



a, b, c = test()

print a,b,c

a, b, c, d = test()

print a,b,c, d



Diez


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


Re: Swaying A Coder Away From Python

2006-05-04 Thread Adam Jones

Rony Steelandt wrote:
> 
> "One problem is that python tools suck," he wrote. Wallace compared the
> various IDEs and other developer tools available to Microsoft's freely
> available Visual Studio Express and called them "toys."
>
> 
>
> What s wrong with VI ???  :)

User error, evidently. Sometimes the interface is more intelligent than
its user, and every time this happens the interface is the one that
gets the bad rap.

Sorry for the snarky comment, but python dev tools do not suck, they
are just generally different from visual studio. There are any number
of good editing platforms for python, visual studio is just not really
one of them.

>
> R_
>
> >> On 4 May 2006 05:24:40 -0700, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
> >>> I'm picking this up via clp on Google Groups. I can't tell what Mr.
> >>> Lundh is referring to. The first line of his post is: "Tim Williams
> >>> wrote" but there's nothing that comes before.
> >
> > Similarly, I'm reading this via comp.lang.python and the original
> > article hasn't shown up at this site.
> >
> > Tim Williams <[EMAIL PROTECTED]> wrote:
> >> I found the web version at.
> >>
>
>
> >> http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html
> >
> > Wherein we find:
> >
> > He also listed a few reasons why C# appeals to him over Python or Java:
> > * anonymous functions (delegates)
> > * a python-like yield statement
> > * a nice type system with generics
> > * interfaces
> > * properties (Yay!!)
> >
> > So that's two of the five Python has, one explicitly acknowledged,
> > plus the combination of lambda and functions-as-first-class-objects
> > is as good as (or better than) "anonymous functions (delegates)".
> > And then we get onto personal preferences as to how to do type
> > systems. That's not a great deal with which to sway someone.
>
>
> --
> ---
> Rony Steelandt
> BuCodi
> rony dot steelandt (at) bucodi dot com
> 
> Visit the python blog at http://360.yahoo.com/bucodi

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


Re: Calling superclass

2006-05-04 Thread Diez B. Roggisch
Florian Lindner wrote:

> Hello,
> I try to call the superclass of the ConfigParser object:
> 
> class CustomizedConfParser(ConfigParser.SafeConfigParser):
> def get(self, section, attribute):
> try:
> return super(CustomizedConfParser, self).get(section,
> attribute)
> # [...]
> 
> 
> but that gives only
> 
> return super(CustomizedConfParser, self).get(section, attribute)
> TypeError: super() argument 1 must be type, not classobj
> 
> I don't really understand the error message.


super works only for newstyle-classes. So additionally extend
CustomizedConfParser from object.

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


Python for Perl programmers

2006-05-04 Thread A.M
Hi,



Is there any efficient online resource or book that help experienced Perl 
programmers to Python?



Thank you,

Alan


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


  1   2   >