Ann: pywinauto 0.1.1 (initial release) released

2006-01-13 Thread Mark Mc Mahon
I'm pleased to announce the first public release of pywinauto 0.1.1

pywinauto is a set of open-source (LGPL) modules for using Python as a GUI
automation 'driver' for Windows NT based Operating Systems (NT/W2K/XP).

SourceForge project page:
http://sourceforge.net/projects/pywinauto

Download from SourceForge
http://prdownloads.sourceforge.net/pywinauto/pywinauto-0.1.1.zip?download

pywinauto-users mailing list
http://lists.sourceforge.net/lists/listinfo/pywinauto-users


pywinauto was nudged into existence by the creation of Watsup
(http://www.tizmoi.net/watsup/intro.html) a similar tool based on
Simon Brunning's (http://www.brunningonline.net/simon/blog/index.html)
winGuiAuto.py.

There are many similar tools that do this (see:
http://tejasconsulting.com/open-testware/feature/gui-test-driver-survey.html)
So how is pywinauto different?
It is still in early stages of development (but is about as functional as
many of the other automation tools).

I think I have designed pywinauto in such a way that it should be easy
to add new actions for Controls. For example imagine

# 10th item on 1st level, 21st item on 2nd, 45th on 3rd
dlg.TreeView.Select(#10\#21\#45)

# Or Possibly (or even both!)
TreeView.Select(path_re = Desktop\\.*\\.*c:\\Temp)

It supports Typing accented/Unicode text (by sending them to the text
area directly - rather then using SendKeys which does not appear to
handle extended/Unicode text well.

It does not require previous analysis of the dialogs to be automated or
for 'reference' information to be saved.

I have also kept in mind that to have language neutral scripts is more
or less impossible - but I am planning to enable a flag that would enable
lookup in previously saved reference information (saved during development
of the script probably) that should enable scripts to run unmodified.
(At least that's the idea - though there are cases where sorting - e.g.
listboxes - might make that impossible).

There is currently no documentation and the examples do double duty as
tests. I am hoping to improve this. Any interest in my first publicly
release code would help my ego greatly :-)


Requirements:
ctypes   http://starship.python.net/crew/theller/ctypes/
Sendkeys http://www.rutherfurd.net/python/sendkeys/index.html
(Optional)   PIL  http://www.pythonware.com/products/pil/index.htm
(Optional)   elementtree  http://effbot.org/downloads/


Very simple test of Notepad automation (notice no time.sleep() ;-)

--- : ---
import application

app = application.Application()
app._start(urc:\windows\system32\notepad.exe)

app.Notepad.MenuSelect(File-PageSetup)

# - Page Setup Dialog 
# Select the 'Letter' combobox item
app.PageSetupDlg.ComboBox1.Select(Letter)

# Now close the dialog
app.PageSetupDlg.Ok.Click ()

# type some text
app.Notepad.Edit.SetText(uTypíng söme tèxt\r\n2nd lïne)

# Close Notepad (and don't save)
app.Notepad.MenuSelect(File-Exit)
app.Notepad.No.Click ()
--- : ---

pywinauto makes significant use of ctypes, I would like to extend my thanks
to Thomas Heller and the whole Python community for producing such
intuitive tools!

Thank you
   Mark


Mark Mc Mahon
24 Plummer Rd., Manchester, NH 03110, USA

PA HREF=http://sourceforge.net/projects/pywinauto;pywinauto 0.1.1/A
Simple Windows GUI automation with Python. (12-Jan-06)
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: HP open source printer drivers are in Python

2006-01-13 Thread Fredrik Lundh
Ben Finney wrote:

  I have a specific question, anybody is familiar?

 Only the omniscient, prescient or telepathic can be familiar with your
 question before you ask it.

so if I know that I'm not familiar with HP's printer drivers, I'm omniscient ?

or is it telepathy that makes it possible for me to communicate with my
brain?  (the latter would of course explain why it doesn't always work...)

coffee time.

/F



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


File Navigation using python

2006-01-13 Thread Danielsen Brian (IFR Contractor External)
Does anyone know how to do file navigation between drives?  I know how to 
navigate up and down within a drive (for example the C:\ drive), but I don't 
know how to change drives.  I'm looking for something like:

os.chgdrv('d:\')

Help

Brian L. Danielsen
   [EMAIL PROTECTED]

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-13 Thread Paul Rubin
Raymond Hettinger [EMAIL PROTECTED] writes:
  I see at least a few cases of
  map(None, field_names, values)
  but it's not clear what the expectation is for the size of the two lists.
...
 Thanks for the additional datapoint.  I'm most interested in the code
 surrounding the few cases with multiple inputs and whether the code is
 designed around equal or unequal length inputs.  The existence of the
 latter is good news for the proposal.  Its absence would be a
 contra-indication.  If you get a chance, please look at those few
 multi-input cases.

ISTR there's also a plan to eliminate map in Python 3.0 in favor of
list comprehensions.  That would get rid of the possibility of using
map(None...) instead of izip_longest.  This needs to be thought through.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: atexit + threads = bug?

2006-01-13 Thread skip

David What would be unreasonable about adding a
David   join_nondaemonic_threads()
David call before the call to
David   call_sys_exitfunc()
David near the beginning of Py_Finalize?

David Instead of _MainThread.__exitfunc having to rely on
David atexit.register to ensure that it gets called,
David join_nondaemonic_threads would call _MainThread.__exitfunc (or
David some functional equivalent).  Both join_nondaemonic_threads and
David call_sys_exitfunc would execute while the interpreter is still
David entirely intact, as the Py_Finalize comment says.

...

David This seems simple.  Am I overlooking something?

A patch? 0.5 wink

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


Re: flatten a level one list

2006-01-13 Thread Peter Otten
Michael Spencer wrote:

 Peter Otten wrote:
 
 If you require len(xdata) == len(ydata) there's an easy way to move the
 loop into C:
 
 def flatten7():
 n = len(xdata)
 assert len(ydata) == n
 result = [None] * (2*n)
 result[::2] = xdata
 result[1::2] = ydata
 return result
 
 $ python -m timeit 'from flatten import flatten6 as f' 'f()'
 1000 loops, best of 3: 847 usec per loop
 $ python -m timeit 'from flatten import flatten7 as f' 'f()'
 1 loops, best of 3: 43.9 usec per loop

 Very nice observation, Peter.  

Thank you :-)

 Easily the winner.  It reminds me of 
 str.translate beating python loops in filtering applications:
 http://groups.google.com/group/comp.lang.python/msg/e23cdc374144a4bd

 What's more, you can generalize your approach to any number of sequences
 and un-equal lengths, with only modest loss of speed:
 
 def interleave(*args, **kw):
  Peter Otten flatten7 (generalized by Michael Spencer)
  Interleave any number of sequences, padding shorter sequences if kw
  pad is supplied
  dopad = pad in kw
  pad = dopad and kw[pad]
  count = len(args)
  lengths = map(len, args)
  maxlen = max(lengths)
  result = maxlen*count*[None]
  for ix, input in enumerate(args):
  try:
  result[ix::count] = input
  except ValueError:
  if dopad:
  result[ix::count] = input + [pad]*(maxlen-lengths[ix])
  else:
  raise
  return result

You don't loose speed because the expensive operation is only executed if
list lengths differ. Two observations:

- list arithmetic like 'input + [pad]*(maxlen-lengths[ix])' should and can
be avoided

- You are padding twice -- once with None, and then with the real thing.

def interleave2(*args, **kw):
 dopad = pad in kw
 pad = kw.get(pad)
 count = len(args)
 lengths = map(len, args)
 maxlen = max(lengths)
 if not dopad and min(lengths) != maxlen:
 raise ValueError
 result = maxlen*count*[pad]
 for ix, input in enumerate(args):
 result[ix:len(input)*count:count] = input
 return result

$ python -m timeit -s 'from interleave_spencer import xdata, ydata,
interleave as i;xdata=xdata[:-1]' 'i(xdata, ydata, pad=None)'
1 loops, best of 3: 69.7 usec per loop
$ python -m timeit -s 'from interleave_spencer import xdata, ydata,
interleave2 as i;xdata=xdata[:-1]' 'i(xdata, ydata, pad=None)'
1 loops, best of 3: 46.4 usec per loop

Not overwhelming, but I expect the difference to grow when the arguments
occupy a significant portion of the available memory.

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


Re: Help me in this please--is Python the answer?

2006-01-13 Thread Ray

bruno at modulix wrote:
 Possibly - but if a programmer is not able to pick on Python in a matter
 of days, then it's a bad programmer that won't be of any help whatever
 the language. So in fact, choosing Python may help you get better
 programmers !-)

You have a point there! :)

 You may also want to have a look at turbogears (roughly similar to
 Django, but probably much more flexible)

Hmm--much more flexible in what sense, Bruno?

Thanks much!
Ray


 My 2 cents
 --
 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


Limiting the size of List and making it Homogeneous

2006-01-13 Thread ankit

Is it possible to limit the size of list in python.
I want to make list of 5 elements. How can I achieve this thing in
python. And one more thing can we declare list to store elements of
same type as in c, C++ we can declare an
array which can have 5 elements of type int.
C, C++:
   int intarr[5] 
How can I achieve this kind of behavior ? 

Thanks

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


Re: Spelling mistakes!

2006-01-13 Thread Antoon Pardon
Op 2006-01-12, [EMAIL PROTECTED] schreef [EMAIL PROTECTED]:

 Antoon But now we are back to my first doubt. Sure unit test will be
 Antoon helpfull in finding out there is a bug. I doubt they are that
 Antoon helpfull in tracking the bug (at least this kind).

 This thread seems to be going in circles.  Maybe it's time to simply drop it
 and move onto other things.  The clear evidence from people who admit to
 having practical experience using unit tests (or pylint or pychecker) is
 that catching misspellings is an extremely shallow bug to find and fix if
 you use the tools at your disposal.

I have no problem with the statement: 

  Spelling errors are easy to fix if you use the tools at your disposal.

But that statement doesn't limit the tools to unit testing.

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


Re: How to get Windows system information?

2006-01-13 Thread Martin P. Hellwig
[EMAIL PROTECTED] wrote:
 Does anybody know how to get the:
 
  Free hard disk space
  Amount of CPU load
  and Amount of RAM used
 
 on windows? I am making an artificial intelligence program that has
 moods based on how much stress the system is under, based on these
 parameters. I think it could possibly be done via COM. I am not looking
 for a cross-platform solution- just something that will work on
 Windows. Thank you for your help!
 

Have a look at WMI* , it's specifically designed to getthat kind of 
stuff, there is also a python layer for WMI**.

* http://msdn.microsoft.com/library/en-us/wmisdk/wmi/wmi_reference.asp
** http://tgolden.sc.sabren.com/python/wmi.html

hth

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


Re: Limiting the size of List and making it Homogeneous

2006-01-13 Thread Erik Max Francis
ankit wrote:

 Is it possible to limit the size of list in python.
 I want to make list of 5 elements. How can I achieve this thing in
 python. And one more thing can we declare list to store elements of
 same type as in c, C++ we can declare an
 array which can have 5 elements of type int.
 C, C++:
int intarr[5] 
 How can I achieve this kind of behavior ? 

Use a list and keep it of length 5.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   There are countless planets, like many island Earths ...
   -- Konstantin Tsiolkovsky
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me in this please--is Python the answer?

2006-01-13 Thread Fredrik Lundh
Adrian Holovaty wrote:

 I would never use TurboGears or Ruby on Rails over Django for any
 performance-intensive Web app. In my opinion, both frameworks make some
 poor design decisions regarding the importance of performance.

I hope you're aware that this sounds a lot like late 90's anti-dynamic-
language propaganda...

I would never use Perl or Python over C++ for any performance-
intensive Web app. In my opinion, both languages make some
poor design decisions regarding the importance of performance.

(you all know all the counter-arguments)

/F



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


Re: Help with super()

2006-01-13 Thread Steven Bethard
David Hirschfield wrote:
 Here's an example that's giving me trouble, I know it won't work, but it 
 illustrates what I want to do:
 
 class A(object):
_v = [1,2,3]
  def _getv(self):
if self.__class__ == A:
return self._v
return super(self.__class__,self).v + self._v
 
v = property(_getv)
  
 class B(A):
_v = [4,5,6]
   b = B()
 print b.v
 
 What I want is for b.v to give me back [1,2,3,4,5,6], but this example 
 gets into a recursive infinite loop, since super(B,self).v is still 
 B._getv(), not A._getv().

You don't actually need to use properties here if you don't want to -- 
the Class.v value can be calculated just once, at the time the class 
statement is executed:

  class A(object):
... class __metaclass__(type):
... def __init__(cls, name, bases, classdict):
... superclass = cls.mro()[1]
... if superclass is object:
... v = []
... else:
... v = list(superclass.v)
... if 'v' in classdict:
... v.extend(cls.v)
... cls.v = v
... v = [1, 2, 3]
...
  class B(A):
... v = [4, 5, 6]
...
  class C(B):
... pass
...
  class D(C):
... v = [7, 8, 9]
...
  A.v
[1, 2, 3]
  B.v
[1, 2, 3, 4, 5, 6]
  C.v
[1, 2, 3, 4, 5, 6]
  D.v
[1, 2, 3, 4, 5, 6, 7, 8, 9]
  B.v is C.v
False

Note that A.__metaclass__.__init__ is called when the A, B, C and D 
class statements are executed.  This code simply looks at the superclass 
of class being created, and creates the appropriate v list.

Note that this approach means that you only create the lists once, 
instead of creating them each time your getv() method is called. 
However, if the list in a superclass changes, the subclass lists will 
not be automatically updated.

HTH,

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


Re: Help me in this please--is Python the answer?

2006-01-13 Thread Ray

Fredrik Lundh wrote:
 I hope you're aware that this sounds a lot like late 90's anti-dynamic-
 language propaganda...

 I would never use Perl or Python over C++ for any performance-
 intensive Web app. In my opinion, both languages make some
 poor design decisions regarding the importance of performance.

 (you all know all the counter-arguments)

Does the comparison between dynamic and static language carry over to
comparison between Django and Turbogear too? Is this what is meant by
Turbogear is much more flexible than Django?

Thanks,
Ray

 
 /F

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


Re: flatten a level one list

2006-01-13 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 Creating a list via list/map/filter just for the side effect is not only
 bad taste,

 ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];ext=lst.extend'
 'for i in a: ext(i)'
 100 loops, best of 3: 1.23 usec per loop
 ~ $ python -m timeit -s'a = zip([range(1000)]*2)'
 'lst=[];filter(lst.extend, a)'
 100 loops, best of 3: 1.63 usec per loop

 it is also slower than an explicit loop. Don't do it.

 Hi, but I found this result instead :
 
 [EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1);
 b=zip(*[a]*2); l=[None]*len(a)*2; e=l.extend l[::2]=b;l[1::2]=b
 100 loops, best of 3: 6.22 msec per loop
 [EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1);
 b=zip(*[a]*2); l=[]; e=l.extend filter(e,b)
 100 loops, best of 3: 7.25 msec per loop
 [EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1);
 b=zip(*[a]*2); l=[]; e=l.extend for x in b: e(x)
 100 loops, best of 3: 10.7 msec per loop
 [EMAIL PROTECTED]:~$
 
 So it seems to be faster than explicit loop. By localizing the l.extend
 name binding, its speed is only 20% slower than  the fastest method.
 May be I have done something wrong in the test ?

I hate to admit it but /my/ post had a bug:

zip([range(1000)]*2) should have been zip(*[range(1000)]*2).

filter() may be ugly, but faster it is.

Peter

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


Re: Why is there no post-pre increment operator in python

2006-01-13 Thread gene tani

[EMAIL PROTECTED] wrote:
 Anyone has any idea on why is there no post/pre increment operators in
 python ?
 Although the statement:
 ++j
 works but does nothing

 +=1 and -=1 inflate your KLOC by .001, but they always work as
expected with integers, it's when you do augmented assignments on lists
and tuples that shit happens

http://zephyrfalcon.org/labs/python_pitfalls.html

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


Re: Template language with XPath support for source code generation?

2006-01-13 Thread Stefan Behnel
bruno at modulix wrote:
 Stefan Behnel wrote:
 I need to generate source code (mainly Java) from a domain specific XML
 language, preferably from within a Python environment (since that's where the
 XML is generated).

 I tried using XSLT, but I found that I need a template system that supports
 Python interaction. I know, lxml's XSLT support is /somewhat/ getting there,
 but even with that, XSLT is so clumsy when it comes to code generation
 (looping constructs and if/else above all), that it would take me tons of 
 XSLT
 code to write what I want.

 I've been looking through Python templating systems all over the place, but I
 just can't find one that supports XPath - which is by far the best thing to
 have when you generate stuff from XML. TAL might be able to get me part of 
 the
 way (at least, it supports some kind of Path expressions, though only for
 object access), but the only available implementation is part of Zope and I
 can't make my code depend on Zope only for a template system.
 
 Zope's implementation can be used freestanding AFAIK. There's also
 SimpleTal that is totally independant from Zope.

Thanks for the quick reply. I didn't know about SimpleTAL.


 My problem is that I want to write as little Python code as possible to make
 the templates (almost) stand alone and thus readable without the backend 
 code.
 I can transform the XML language to a more usable XML format beforehand, no
 problem, but I then need to access the result from the template - and that's
 almost impossible without XPath.

 Does anyone have an idea what I could use? Any hints are helpful.
 
 Perhaps a TAL + elementTree combo could do ? (first parse the source XML
 with elementTree, then pass the resulting tree as the context of the
 ZPT/SimpleTal template)

SimpleTAL has ElementTree integration. Wouldn't work with lxml, though, as it
uses internals of ElementTree. Problem is that SimpleTAL requires the tree as
a context object, which is difficult to produce from lxml. It should work when
relying on Python code for access, although that removes some of the beauty.
I'll have to see where that gets me...

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


Re: Newcomer question wrt variable scope/namespaces

2006-01-13 Thread gene tani

Florian Daniel Otel wrote:
 Hello all,


 Attached are 3 small python scripts that illustrate my problem. The
 first one uses string tuples and behaves as expected. The other two
 use dictionaries and (resp.) lists and illustrate my problem

 TIA for any pointers,

 Florian

 P.S. I am not reading the newsgroup / subscribed to the mailing list,
 so please Cc: me on the replys.

ok pointers: put the code in your post (inline, not as attachments),
they're small, like you said.  And maybe you ahve access to google
groups or gmane, hmmm?

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


Re: flatten a level one list

2006-01-13 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 David Murmann wrote:

  # New attempts:
  from itertools import imap
  def flatten4(x, y):
  '''D Murman'''
  l = []
  list(imap(l.extend, izip(x, y)))
  return l

 well, i would really like to take credit for these, but they're
 not mine ;) (credit goes to Michael Spencer). i especially like
 flatten4, even if its not as fast as the phenomenally faster
 flatten7.

 Me too. And expand a bit on flatten4, I got this interesting result.
 
 [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
 import itertools; a=zip(xrange(1000),xrange(1000)) l=len(a);
 li=[None]*l*2;li[::2]=range(1000); li[1::2]=range(1000)
 1000 loops, best of 3: 318 usec per loop
 
 [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
 import itertools,psyco; a=zip(xrange(1000),xrange(1000));li=[]
 filter(li.extend,a)
 1000 loops, best of 3: 474 usec per loop

For a fair comparison you'd have to time the zip operation.
 
 Still 50% slower but it has the advantage that it works on all kinds of
 sequence as they can be efficiently izip() together.

Creating a list via list/map/filter just for the side effect is not only bad
taste,

~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];ext=lst.extend'
'for i in a: ext(i)'
100 loops, best of 3: 1.23 usec per loop
~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];filter(lst.extend,
a)'
100 loops, best of 3: 1.63 usec per loop

it is also slower than an explicit loop. Don't do it.

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


Changing fill in tkinter

2006-01-13 Thread venk
Hi,
 I would like to know how to change the fill of things we put in a
tkinter's canvas. for example, if i create a rectangle and i would want
to change the fill of the rectangle once it is clicked... can we do
that?

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


Re: flatten a level one list

2006-01-13 Thread bonono

Peter Otten wrote:
 [EMAIL PROTECTED] wrote:

  David Murmann wrote:

   # New attempts:
   from itertools import imap
   def flatten4(x, y):
   '''D Murman'''
   l = []
   list(imap(l.extend, izip(x, y)))
   return l

  well, i would really like to take credit for these, but they're
  not mine ;) (credit goes to Michael Spencer). i especially like
  flatten4, even if its not as fast as the phenomenally faster
  flatten7.
 
  Me too. And expand a bit on flatten4, I got this interesting result.
 
  [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
  import itertools; a=zip(xrange(1000),xrange(1000)) l=len(a);
  li=[None]*l*2;li[::2]=range(1000); li[1::2]=range(1000)
  1000 loops, best of 3: 318 usec per loop
 
  [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
  import itertools,psyco; a=zip(xrange(1000),xrange(1000));li=[]
  filter(li.extend,a)
  1000 loops, best of 3: 474 usec per loop

 For a fair comparison you'd have to time the zip operation.

  Still 50% slower but it has the advantage that it works on all kinds of
  sequence as they can be efficiently izip() together.

 Creating a list via list/map/filter just for the side effect is not only bad
 taste,

 ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];ext=lst.extend'
 'for i in a: ext(i)'
 100 loops, best of 3: 1.23 usec per loop
 ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];filter(lst.extend,
 a)'
 100 loops, best of 3: 1.63 usec per loop

 it is also slower than an explicit loop. Don't do it.

Hi, but I found this result instead :

[EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1);
b=zip(*[a]*2); l=[None]*len(a)*2; e=l.extend l[::2]=b;l[1::2]=b
100 loops, best of 3: 6.22 msec per loop
[EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1);
b=zip(*[a]*2); l=[]; e=l.extend filter(e,b)
100 loops, best of 3: 7.25 msec per loop
[EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1);
b=zip(*[a]*2); l=[]; e=l.extend for x in b: e(x)
100 loops, best of 3: 10.7 msec per loop
[EMAIL PROTECTED]:~$

So it seems to be faster than explicit loop. By localizing the l.extend
name binding, its speed is only 20% slower than  the fastest method.
May be I have done something wrong in the test ?

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


Re: Is 'everything' a refrence or isn't it?

2006-01-13 Thread Bryan Olson
Mike Meyer wrote:
 Bryan Olson writes:
 
[EMAIL PROTECTED] wrote:

The reason is that I am still trying to figure out
what a value is myself.  Do all objects have values?

Yes.
 
 
 Can you justify this, other than by quoting the manual whose problems
 caused this question to be raised in the first place?

The Python manual's claim there is solidly grounded. The logic
of 'types' is reasonably well-defined in the discipline. Each
instance of a type takes exactly one element from the type's
set of values (at least at a particular time).


What the value of object()?  A few weeks ago I turned
to that page for enlightenment, with the results I reported.

I think type 'object' has only one value, so that's it.
 
 In that case, they should all be equal, right?
object() == object()
 
 False
 
 Looks like they have different values to me.

Whether the '==' operation conforms to your idea of what equality
means is unclear. Maybe I was wrong, and the object's identity
is part of its abstract state.

 Or maybe an object is valueless, in spite of what the manual says.

We know that's not true.


-- 
--Bryan

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


Re: Options enabled under optimization

2006-01-13 Thread Fredrik Lundh
Naveen H.S. [EMAIL PROTECTED] wrote:

 I had mailed yesterday about the following topic to know the flags or
 options that are enabled when -O,-O2,-O3,-Os options are enabled.
 As mentioned below I was given this mail id to contact.

Unfortunately, you seem to have missed the relevant portions of that
mail:

Sounds like a compiler question, not a Python question.

Try the documentation or the source code for the compiler you're
using.

On the outside chance your question is actually Python-related
/snip/ 

 Ex Some flags that are enabled when -O is enabled is
 -fomit-frame-pointer
 -fdefer-pop etc.I would like to know all the flags that will be enabled.

For Python, the answer is none at all.

$ python -fomit-frame-pointer
Unknown option: -f
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `python -h' for more information.

For gcc, the answer can be found in the gcc documentation, available
from:

http://gcc.gnu.org/

(this is the first hit if you google for gcc)

The answer to your question is only a few clicks away from the front-
page:

http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

(this is the first hit if you google for gcc optimization options)

Note that the details may differ between compiler versions; use the
manual link on the gcc homepage locate the right documentation for
the version you're using.

 I am writing this mail with a lot of hopes; I hope that I would not be
 disappointed this time.

I'm afraid it looks like you're mailing questions to random addresses
based on sloppy google searches, and ignoring the replies.  That's
pretty disappointing.  We really expected more from you.

/F



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


Re: Is 'everything' a refrence or isn't it?

2006-01-13 Thread Mike Meyer
Bryan Olson [EMAIL PROTECTED] writes:
 [EMAIL PROTECTED] wrote:
 The reason is that I am still trying to figure out
 what a value is myself.  Do all objects have values?
 Yes.

Can you justify this, other than by quoting the manual whose problems
caused this question to be raised in the first place?


 What the value of object()?  A few weeks ago I turned
 to that page for enlightenment, with the results I reported.
 I think type 'object' has only one value, so that's it.

In that case, they should all be equal, right?

 object() == object()
False

Looks like they have different values to me.

Or maybe an object is valueless, in spite of what the manual says.

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flatten a level one list

2006-01-13 Thread bonono

Peter Otten wrote:
 [EMAIL PROTECTED] wrote:

  David Murmann wrote:

   # New attempts:
   from itertools import imap
   def flatten4(x, y):
   '''D Murman'''
   l = []
   list(imap(l.extend, izip(x, y)))
   return l

  well, i would really like to take credit for these, but they're
  not mine ;) (credit goes to Michael Spencer). i especially like
  flatten4, even if its not as fast as the phenomenally faster
  flatten7.
 
  Me too. And expand a bit on flatten4, I got this interesting result.
 
  [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
  import itertools; a=zip(xrange(1000),xrange(1000)) l=len(a);
  li=[None]*l*2;li[::2]=range(1000); li[1::2]=range(1000)
  1000 loops, best of 3: 318 usec per loop
 
  [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
  import itertools,psyco; a=zip(xrange(1000),xrange(1000));li=[]
  filter(li.extend,a)
  1000 loops, best of 3: 474 usec per loop

 For a fair comparison you'd have to time the zip operation.

  Still 50% slower but it has the advantage that it works on all kinds of
  sequence as they can be efficiently izip() together.

 Creating a list via list/map/filter just for the side effect is not only bad
 taste,

 ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];ext=lst.extend'
 'for i in a: ext(i)'
 100 loops, best of 3: 1.23 usec per loop
 ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];filter(lst.extend,
 a)'
 100 loops, best of 3: 1.63 usec per loop

 it is also slower than an explicit loop. Don't do it.
ah, stand corrected.

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


Re: Restart process with SIGHUP

2006-01-13 Thread LukasMeyerUK
Got it working now. It was a silly character pid instead of an int..

int(pid) fixed it. 

Thanks anyway!

regards, Lukas

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


Re: Why keep identity-based equality comparison?

2006-01-13 Thread Antoon Pardon
Op 2006-01-12, Mike Meyer schreef [EMAIL PROTECTED]:
 Antoon Pardon [EMAIL PROTECTED] writes:
 Op 2006-01-11, Mike Meyer schreef [EMAIL PROTECTED]:

[ BIG CUT ]

I'm going to drop this part. I disagree with you and think
I can show some of your argument invalid. Hoever I also doubt
something fruitfull can come from continuing this. Lets agree
to disagree.

 IMO it would be better if it was possible to associate some kind
 of order function with the container. Because the order most usefull
 for comparing between two instances doesn't need to be the most usefull
 order in finding an element from a container.

 No, it wouldn't. Order relationships are a property of the type, not
 the container. The order relationships are right where they belong -
 attached to the type.

Order relationships are only a property of the type in a particular
sense. There certainly is not a one on one relationship between
order relationships and types. A type can have multiple order relationships
all usefull in different circumstances. If a specific order is
only usefull in the context of a spefic container I see no problem
with associating the order with the container.

 That notwithstanding, it's often practical to be
 able to override the order function for some specific method (and
 would be even if the order function were associated with the container
 instead of the type), so some of the methods that use order allow you
 to provide a function to use for them. If you really want a container
 type that has an order function associated with it, you can write
 one. If you want it made part of the language, you'll have to provide
 a use case.

Fair enough. Take the heapqueue module. The times that I had need
for a heapqueue this module was useless to me. The reason always
boiled down to the fact that the order defined on the object
(as far as there was one) was not the order in which I wanted
the objects processed. e.g. I want a heapqueue of sets that gives
priority according to the number of elements in the set. Or I have
two heapqueues each of intervals. The first gives priority according
to the low value, the second gives priority according the the high
value.

 algorithm on a container of them, but such an order is in general
 less usefull than the superset ordering when you are manipulating
 sets.

 And you're free to implement a subclass of sets that does that.

But that is not usefull to me. Take sets. It's been a while so
I'm not sure I can dig it back up, but I once had an algorithm
manipulating sets, where this manipulation would involve the
normal superset order. This algorithm had two charateristics.

1) Manipulating certain sets, made the manipulation of other
   sets unnecessary.

2) Manipulating smaller sets was faster than manipulating
   larger sets.

3) Sets were constantly added and removed from the manipulating
   pool.

These characteristics made this a natuaral candidate for a heapqueue
that used the number of elements as (inverse) priority.

However the manipulation of a single set needed the normal
superset relationship as order relation.

So making a subclass of sets with an order usefull for the
heapqueue would only be a marginal improvement to the
existing situation.

 If you
 want to argue that the builtin sets should do that, you can - but
 that's unrelated to the question of how the comparison operators
 behave for the rest of the bulitin types.

What I argue is that there is no single order for a specific type.
There can be an order that is most usefull in general but which order
is usefull at a specific point depends on the context. Sometimes
this context is the container that the types belongs to, like
a heapqueue. Associating that order with the container seems to
most natural to treat this kind of circumstances.

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


Re: how do real python programmers work?

2006-01-13 Thread Alan J. Salmoni
Hi Brian,

I'm sure I don't qualify as an experienced Python programmer, but I
write lots of code usually for statistical analysis (via numarray) or
for GUI work.

The way I work is to use an editor and Idle for interactive testing of
small routines.

My choice of editor is SciTE. I'll have different modules (both working
and testing modules) in a range of different tabs and use the built-in
execute code function (F5) to run and check errors. Idle is then used
to test small functions and explore when I need to. The editor gets
more of the GUI work and Idle gets more of the statistics work - the
ability to test routines on the fly is enormously helpful and quite a
productive way to work.

Say I was looking at some linear algebra and I want an SSCP matrix.
Just enter the data into variable 'X' then:

 Xd = X - average(X) # deviations matrix
 Xdt = transpose(Xd)
 SSCP = dot(Xdt, Xd)

and there's my matrix. However, the useful thing is that the transposed
X matrix is still there so if I go on to a multiple regression, I can
use it there too.  For statistics, it's tremendously useful,
particularly if the analysis doesn't go as planned (eg, presence of
outliers) and further exploration is needed. Perhaps later I need the
variances of each variable:

 diagonal(SSCP)

And out they appear without having to go through an entire program.
Even though Python is slower than well-written Fortran, the interactive
nature can make statistical analysis quicker.

All the best!

Alan.

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


Re: Limiting the size of List and making it Homogeneous

2006-01-13 Thread gene tani

ankit wrote:
 Is it possible to limit the size of list in python.
 I want to make list of 5 elements. How can I achieve this thing in
 python. And one more thing can we declare list to store elements of
 same type as in c, C++ we can declare an
 array which can have 5 elements of type int.
 C, C++:
int intarr[5]
 How can I achieve this kind of behavior ?

 Thanks

- ring(circular) buffers overwrite oldest elements when they're flagged
as at their limit, is that what you want?:

http://www.onlamp.com/lpt/a/5828

you can write whatever type checks you want in the append() methods

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


Re: how do real python programmers work?

2006-01-13 Thread bruno at modulix
Barbier de Reuille Pierre wrote:
 On 12 Jan 2006 12:20:50 -0800
 bblais [EMAIL PROTECTED] wrote:
 
 
Hello,

(snip)
 
 
 Well, I think it will depend on your project ...
 If you're developing GUI application, you will have trouble using the
 python shell. At least you will need a special, customized shell that
 will take care of launching the main loop of your GUI and let you enter
 commands. 

Well, most of your code should be runnable/testable without the GUI
part, so that may not be such a big problem.

(snip)

-- 
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: Converting a string to an array?

2006-01-13 Thread Paul Rubin
Tim Chase [EMAIL PROTECTED] writes:
 The closest hack I could come up with was
 
   import random
   s = abcdefg
   a = []
   a.extend(s)
   random.shuffle(a)
   s = .join(a)

You could use

import random
s = list(abcdefg)
random.shuffle(s)
s = .join(s)

which cuts down the clutter slightly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I make a dictionary that marks itself when it's modified?

2006-01-13 Thread Duncan Booth
Bengt Richter wrote:

 You are right, but OTOH the OP speaks of a flagging the dict as
 modified. If she made e.g., modified a property of the dict
 subclass, then retrieving the the modified flag could dynamically
 check current state repr vs some prior state repr. Then the question
 becomes modified w.r.t. what prior state? 
 
 This lets the OP ask at any time whether the dict is/has_been
 modified, but it's not a basis for e.g., a modification-event callback
 registry or such. 
 
Good point. So the following matches what was asked for, although 
depending on the actual use pattern it may or may not match what is 
required:

-- tracked.py -
import cPickle, md5
class TrackedDict(dict):
def __init__(self, *args, **kw):
dict.__init__(self, *args, **kw)
self.resetModified()

def __getstate__(self):
return dict(self)
def __setstate__(self, d):
self.update(d)

def _gethash(self):
pickle = cPickle.dumps(self)
hash = md5.new(pickle).digest()
return hash

@property
def modified(self):
return self._hash != self._gethash()

def resetModified(self):
self._hash = self._gethash()

if __name__=='__main__':
d = TrackedDict(x=[])
assert not d.modified
d['a'] = [1, 2, 3]
assert d.modified
d.resetModified()
assert not d.modified
d['a'].append(4)
assert d.modified
assert d== {'x':[], 'a':[1, 2, 3, 4]}
assert d==cPickle.loads(cPickle.dumps(d))
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading from input file.

2006-01-13 Thread Sheldon
Sorry Mike, after seeing so many experts beat up others for not being
as smart as they are, I intrepreted your words incorrectly - my
apologies. I am not in the least bit against impproving my programming.
I liked what you did and thanks for the pointers.

Sheldon

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


Re: void * C array to a Numpy array using Swig

2006-01-13 Thread Krish
Thanks Jon Much

I will implement your method for the time being. I am sure there is
some method which doesn't copy the data but uses the existing data.

I mean essentially we should build a PyArrayObject with the data intact
and other parameters filled. If someone sheds some light, would be
awesome. I am gonna try it  this weekend. 

Appreciated
Krish

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


Re: decode unicode string using 'unicode_escape' codecs

2006-01-13 Thread Steven Bethard
aurora wrote:
 I have some unicode string with some characters encode using python  
 notation like '\n' for LF. I need to convert that to the actual LF  
 character. There is a 'unicode_escape' codec that seems to suit my purpose.
 
 encoded = u'A\\nA'
 decoded = encoded.decode('unicode_escape')
 print len(decoded)
 3
 
 Note that both encoded and decoded are unicode string. I'm trying to 
 use  the builtin codec because I assume it has better performance that 
 for me  to write pure Python decoding. But I'm not converting between 
 byte string  and unicode string.
 
 However it runs into problem in some cases.
 
 encoded = u'€\\n€'
 decoded = encoded.decode('unicode_escape')
 Traceback (most recent call last):
   File g:\bin\py_repos\mindretrieve\trunk\minds\x.py, line 9, in ?
 decoded = encoded.decode('unicode_escape')
 UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in  
 position 0: ordinal not in range(128)

Does this do what you want?

  u'€\\n€'
u'\x80\\n\x80'
  len(u'€\\n€')
4
  u'€\\n€'.encode('utf-8').decode('string_escape').decode('utf-8')
u'\x80\n\x80'
  len(u'€\\n€'.encode('utf-8').decode('string_escape').decode('utf-8'))
3

Basically, I convert the unicode string to bytes, escape the bytes using 
the 'string_escape' codec, and then convert the bytes back into a 
unicode string.

HTH,

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


Re: Changing fill in tkinter

2006-01-13 Thread Eric Brunel
On 13 Jan 2006 01:43:42 -0800, venk [EMAIL PROTECTED] wrote:

 Hi,
  I would like to know how to change the fill of things we put in a
 tkinter's canvas. for example, if i create a rectangle and i would want
 to change the fill of the rectangle once it is clicked... can we do
 that?

Not sure if I correctly understand your question, but you seem to look for  
itemconfigure:

 from Tkinter import *
 root = Tk()
 c = Canvas(root)
 c.pack()
 r = c.create_rectangle(20, 20, 60, 60)
 c.itemconfigure(r, fill='blue')

Is that what you were after?

HTH
-- 
python -c print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: different versions for 2.3.4 documentation

2006-01-13 Thread Manlio Perillo
Martin v. Löwis ha scritto:
 Manlio Perillo wrote:
 
I'm only a bit curious, but why documentation from
http://www.python.org/ftp/python/2.3.4/Python-2.3.4.tar.bz2
and
http://www.python.org/ftp/python/doc/2.3.4/latex-2.3.4.tar.bz2
differ?
 
 
 It appears that the latex-* set really comes from the 2.4 branch,
 somehow. That must be a mistake.
 

Well, the same happens for 2.3.5...
And I still don't have checked 2.4.x releases.



Thanks and regards  Manlio Perillo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is 'everything' a refrence or isn't it?

2006-01-13 Thread Sybren Stuvel
Mike Meyer enlightened us with:
 I think type 'object' has only one value, so that's it.

 In that case, they should all be equal, right?

 object() == object()
 False

You compare instances of the type 'object'. They both have one value:

 object()
object object at 0xb7ddb438
 object()
object object at 0xb7ddb440

So the claim type 'object' has only one value is true. It's just not
the same value for all instances.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie with some doubts.

2006-01-13 Thread Peter Maas
Claudio Grondi schrieb:
 Im newbie to Python (I found it three weeks ago) , in fact Im newbie to
 programming. I'm being reading and training with the language, but I
 still wondering about what Classes are used to. Could you please give
 me some examples??
[...]
 I don't know any really good examples which were able to demonstrate 
 what Classes are good for and I am in programming already for decades.

Then you have in all those decades for sure never seen a GUI program
done with the Win32 API (not OO, ugly, hard to grasp) and a Delphi
equivalent (OO, elegant, easy).

 There is actually no real need for usage of Classes. 

This is your opinion, not a fact as your wording suggests. If the OP
is asking for examples it doesn't make sense to answer Hey, I don't
know any examples.

  The notion, that they could be useful comes eventually with longer
  programming experience and/or with growing size of the code library.

I don't think so. OO is modeled after human reasoning. Look e.g.
at phrases like Bob calls a friend, Bob learns math.

What is better:

Bob.call(friend) or human_call(Bob, friend), Bob.learn(math) or
human_learn(Bob, math)?

On the other hand there are cases where the emphasis is on the
verb, e.g. compute the sine of alpha: sin(alpha) is perfect,
no need to code alpha.sin(). Therefore I like hybrid languages
like python giving the programmer the freedom to choose an
appropriate model.

  If you can avoid to learn  about them, at least at the beginning,
  take the chance - it will save you much trouble and help to get
  things done.

Excuse me, but to present your personal experience as a law of
nature is not very helpful for a newbie seeking for advice not
for propaganda. It is plain wrong to claim that procedural
programming is kind of natural and OOP is rocket science.

 I for myself try to avoid classes where I can, especially
  inheritance, because I consider the latter in most cases evil.

There are terrible OO libraries out there but this is not
a genuine feature of OOP. Bad code can be written in lots
of ways.

  There are sure many others who can't imagin to program
  without classes, so don't conclude that there is a
  contradiction here - it's just the question of taste

It's not a question of taste it's a question of the kind
of problem to solve.

Peter Maas, Aachen
-- 
http://mail.python.org/mailman/listinfo/python-list


Adding an extension class using C++

2006-01-13 Thread shlychkov
I'm building a C++ program that encapsulates Python inside and has a
few extension classes with member variables and member functions. So
far almost everything is successful, I'm able to run scripts through
the utility, I can instantiate instances of my extension classes, I can
read/write member variables of the classes through class objects, but I
just cannot make member functions work properly. When I call a
function, I get the following message:
  exceptions.TypeError: 'NoneType' object is not callable
The way I extend Python is nothing (as far as I can see) different from
the documented way of doing it. This is my script:

from MyModule import *

def main():
MyInstance = MyClass()

MyInstance.memberVar1 = 1
MyInstance.memberVar2 = 20
MyInstance.memberVar3 = 300

MyInstance.print()

If I comment out the last line, I get no messages, meaning good. I also
tried printing out values after I set them and it works flawlessly.
I would really appreciate if anybody could help me, because I'm at a
loss. It probably is something really stupid, but I just fail to see it
right now.

Please help.
Thanks!
Alex.

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


Re: how do real python programmers work?

2006-01-13 Thread Barbier de Reuille Pierre
On 12 Jan 2006 12:20:50 -0800
bblais [EMAIL PROTECTED] wrote:

 Hello,
 
 Let me start by saying that I am coming from a background using Matlab
 (or Octave), and C++.  I am going to outline the basic nuts-and-bolts
 of how I work in these languages, and ask for some help to find out
 how the same thing is done in Python.  I am not sure what the
 standard is.
 
 In C++, I open up an editor in one window, a Unix shell in another.  I
 write the code in the editor, then switch to the shell window for
 compile and run.  I then go back to the editor for modifications, and
 then compile and run in the shell window.
 
 In Matlab, I do much the same thing, except there is no compile phase.
 I have the editor on one window, the Matlab interactive shell in the
 other.  I often make a bunch of small scripts for exploration of a
 problem, before writing any larger apps.  I go back and forth editing
 the current file, and then running it directly (Matlab looks at the
 time stamp, and automagically reloads the script when I modify it).
 
 In Python, there seems to be a couple ways of doing things.   I could
 write it in one window, and from a Unix shell call
python myscript.py
 and be like C++, but then I lose the interactiveness which makes
 prototyping easier.  If I use the python shell, I can use import (and
 reload), or execfile perhaps.
 
 How do experienced python programmers usually do it?  Is there a
 usually about it, or is it up to personal taste?  Are there any
 convenient ways of doing these things?
 
 I realize this is a pretty newbie question, but it could possibly save
 me hours of time if there is a better way to work.
 
 
   thanks,
 
 Brian Blais
 

Well, I think it will depend on your project ...
If you're developing GUI application, you will have trouble using the
python shell. At least you will need a special, customized shell that
will take care of launching the main loop of your GUI and let you enter
commands. But I don't think this is a big help to build GUI ... 
Now, what I do for other stuffs (or when I have access to such a
modified shell). First, when I develop an object, I quit and
reload my script after each modification, mainly because problems
arises quickly with different variables with difference version of the
same class and you have no way to exactly know what variable hold what
version of the class. However, when I'm developing algorithms I reload
the modules while keeping the shell launched. Only at the very end do I
quit and relaunch to be 100% sure my algorithm is working with the
new versions of the modules ...

Pierre

-- 
You will overcome the attacks of jealous associates.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flatten a level one list

2006-01-13 Thread Robin Becker
Peter Otten wrote:
..
 - You are padding twice -- once with None, and then with the real thing.
 
 def interleave2(*args, **kw):
  dopad = pad in kw
  pad = kw.get(pad)
  count = len(args)
  lengths = map(len, args)
  maxlen = max(lengths)
  if not dopad and min(lengths) != maxlen:
  raise ValueError
  result = maxlen*count*[pad]
  for ix, input in enumerate(args):
  result[ix:len(input)*count:count] = input
  return result
 
 $ python -m timeit -s 'from interleave_spencer import xdata, ydata,
 interleave as i;xdata=xdata[:-1]' 'i(xdata, ydata, pad=None)'
 1 loops, best of 3: 69.7 usec per loop
 $ python -m timeit -s 'from interleave_spencer import xdata, ydata,
 interleave2 as i;xdata=xdata[:-1]' 'i(xdata, ydata, pad=None)'
 1 loops, best of 3: 46.4 usec per loop
 
 Not overwhelming, but I expect the difference to grow when the arguments
 occupy a significant portion of the available memory.
 
 Peter
very nice indeed; another generalization is to allow truncation as well

def interleave(*args,**kw):
 Peter Otten flatten7 (generalized by Michael Spencer and Robin Becker)
 Interleave any number of sequences, padding shorter sequences if kw pad
 is supplied or truncating if truncate=True is specified

  interleave([1,3,5], [2,4,6]) == [1,2,3,4,5,6]
 True
  interleave([1,2,3]) == [1,2,3]
 True
  interleave(*[[1,2,3]]*10) == [1]*10+[2]*10+[3]*10
 True
  interleave(range(0,1000,2),range(1,1000,2)) == range(1000)
 True
  interleave([1,2],[3,4,5])
 Traceback (most recent call last):
 ...
 ValueError: Minimum length=2 != Max length=3
  interleave([1,3],[2,4,6], pad = None) == [1,2,3,4,None,6]
 True
  interleave([1,3],[2,4,6],truncate=True) == [1,2,3,4]
 True
  interleave([1,2],[3,4,5],pad='aaa',truncate=1)
 Traceback (most recent call last):
 ...
 AssertionError: Cannot specify both truncate=True and pad='aaa'
 
 dopad = pad in kw
 pad = kw.get(pad)
 dotrunc = bool(kw.get('truncate',False))
 assert not (dotrunc and pad), \
 'Cannot specify both truncate=True and pad=%r' % pad
 count = len(args)
 lengths = map(len,args)
 maxlen = max(lengths)
 minlen = min(lengths)
 if dotrunc:
 result = minlen*count*[None]
 for ix, input in enumerate(args):
 result[ix::count] = input[:minlen]
 else:
 if not dopad and minlen!=maxlen:
 raise ValueError('Minimum length=%d != Max length=%d'
 % (minlen,maxlen))
 result = maxlen*count*[pad]
 for ix, input in enumerate(args):
 result[ix:len(input)*count:count] = input
 return result

def _test():
 import doctest, interleave
 return doctest.testmod(interleave)

if __name__ == __main__:
 _test()

-- 
Robin Becker

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


Re: Accessing Windows file metadata?

2006-01-13 Thread John Rhoads

Probably somebody more deeply into this will soon give you a better answer, 
but I'll
try to give a better-than-nothing answer.

The Properties metadata that you see in the shell can come from several places.
The oldest, commonest source is from Microsoft Office files. These have a 
compound
structure associated with OLE Object Linking and Embedding and the metadata 
is just one
of a lot of things stuck in there besides the Word text or Excel numbers 
you see in the
application.

Getting to it from Python is via COM. See Mark Hammond and Andy Robinson's 
book
Python Programming in Win32 for the general approach. Perhaps the easiest 
way to
get this metadata is using DSOFILE.DLL that was released as an example a long
time ago by Microsoft (it's not an OS file, you have to install it yourself). 


The following article gives a VBScript example that you can
use as a template for your Python.

http://www.microsoft.com/technet/community/columns/scripts/sg0305.mspx

As I said, the OLE metadata has been around for a long time. With Windows 
2000, MS
extended the idea to any NTFS file so that you have an open-ended ability to 
associate named attributes like author, title, keywords or custom attributes 
of your
own to any file on an NTFS partition.

Unfortunately DSOFILE does not help with this (at least I don't think so!), 
so you'd need
to deal with the OS at a somewhat uglier level. And obviously you need Win2K 
or better.

Look at \win32com\test\testStorage.py in the win32 python package for an 
example.

Hope this helps,


John Rhoads


 I'm looking for a method by which to access Windows files metadata and
 have not been able to find anything in the standard modules or via
 Google - what is the standard approach?
 
 Shamefully I really do not understand Windows file system - e.g. is
 properties metadata attached to the file?if I change that metadata
 do I change the file's hash?  how is the metadata structured?  or is
 the properties metadata simply derived upon access?
 
 Either way, is there a module or method to access this metadata (I'd
 hope there was a metadata dictionary for each file, but that may be a
 sign I've been spoiled by Python) ?
 
 EP
 


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


Re: Freezing

2006-01-13 Thread bearophileHUGS
Raymond Hettinger:

I'm curious whether you've had an actual use for dictionaries as keys.

I've never had this need (probably because it's an unsupported thing to
do too).


Likewise, how about frozensets?  Have you had occasion to use them as keys?  
They were created to support sets of sets, yet even that doesn't come-up 
often.

I use sets all the time. And doing a little of mathematics it's rather
common to need subsets too, I have had this need 3-4 times. But the
implementation of subsets is broken (= no dynamic subsets allowed)
and frozen subsets aren't much useful.


So why build a mechanism to automate a process that no one uses?

You are right, frozedicts aren't much useful.
Maybe that freezing protocol was useful for user defined objects too.


Also note that Guido has said over and over that tuples are NOT frozenlists. 
Even with a mechanism to freeze lists, tuples won't go away.

Lists and fronzensets look like a duplication to me, so the freezing
operation was meant to remove them too.


The term freezing inaccurately suggests an in-place operation; however, the 
PythonWay(tm) is to create new objects (i.e. given a mutable set s, the result 
of frozenset(s) is a new container).

It seems sometimes Py doesn't follow its own PythonWay(tm)  :-)
But I agree that sometims consistency can be useful.

Thank you for your (good as usual) comments, Raymond.
(Strong rigour is necessary near the last stages, before the actual
implementation of an idea, but in most cases the creation of ideas
works better in a tolerant and more relaxed environment.)

-

Mike Meyer:

Freezing in place is problematical. For this to work as intended, all the 
values in the container have to be frozen as well.

Right, I was talking about deep (recursive) freezing in the original
post too.


Actually, I like the len model, which would be a new builtin that uses the 
__freeze__ method.

Well, I presume this is a matter of personal tastes and consistency
too. This time I appreciate the freeze() too, but probably some people
can think that adding .len, .copy(), .del(), .freeze() methods to most
objects is more regular:

len(l)   l.len
copy.copy(l) l.copy()
|l|   freeze(l)  l.freeze()
del ll.del()

Bye,
bearophile

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


Re: Changing fill in tkinter

2006-01-13 Thread venk
yes, it was a stupid mistake from my part in not pondering over the api
fully. forgive me. anyways, ii was just looking for item configure. (I
was spending all my time searching google rather than reading the api
sincerely. duh...)

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


Newcomer question wrt variable scope/namespaces

2006-01-13 Thread Florian Daniel Otel
Hello all,

As the subject says, I am a newcomer to Python and I have a newcomer
question wrt namespaces and variable scope. Obviously, I might be
missing smth obvious, so TIA for the patience and/or pointers to
relevant resources

My problem: I just discovered (by mistake) that attempting to assign a
value to a non-local dictionary/list member does NOT generate an 
UnboundLocalError exception and the assignment is preserved upon
exiting that scope (i.e. function). This would violate the python
scoping rules where a variable in a global scope can only be
referenced to (and not assigned to)  -- unless declared as global.

Attached are 3 small python scripts that illustrate my problem. The
first one uses string tuples and behaves as expected. The other two
use dictionaries and (resp.) lists and illustrate my problem

TIA for any pointers,

Florian

P.S. I am not reading the newsgroup / subscribed to the mailing list,
so please Cc: me on the replys.


001-scope.py
Description: application/python


002-scope.py
Description: application/python


003-scope.py
Description: application/python
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Help with super()

2006-01-13 Thread David Hirschfield
Yes, indeed that does work.
I tried using __mro__ based on some code that showed how super() works 
in pure-python, but I got lost.
I think this makes that clear...tho' I hate squishing around in instance 
innards like this...

Thanks a bunch, I'm sure I'll have more questions,
-Dave

Paul McNett wrote:

 David Hirschfield wrote:

 Is there a way to get what I'm after using super()?


 Probably.


 The idea is that I could have a chain of subclasses which only need 
 to redefine _v, and getting the value of v as a property would give 
 me back the full chain of _v values for that class and all its 
 ancestor classes.


 Does this work? :

 class A(object):
   _v = [1,2,3]

   def _getv(self):
 ret = []
 mroList = list(self.__class__.__mro__)
 mroList.reverse()
 for c in mroList:
   print c, ret
   if hasattr(c, _v):
 ret += c._v
 return ret

   v = property(_getv)


 class B(A):
   _v = [4,5,6]

 b = B()

 print b.v



-- 
Presenting:
mediocre nebula.

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


Re: Is 'everything' a refrence or isn't it?

2006-01-13 Thread Fredrik Lundh
Sybren Stuvel wrote:

 Mike Meyer enlightened us with:
  I think type 'object' has only one value, so that's it.
 
  In that case, they should all be equal, right?
 
  object() == object()
  False

 You compare instances of the type 'object'. They both have one value:

  object()
 object object at 0xb7ddb438
  object()
 object object at 0xb7ddb440

 So the claim type 'object' has only one value is true. It's just not
 the same value for all instances.

You're comparing identities, not values.  The value is the set of things that
you can access via an object's methods (via the type).  The identity is not,
in itself, a part of the value.

Python doesn't query the object to determine it's type or identity, but it
always has to query the object to access the value.

A look at the C implementation of a typical object might help:

typedef struct {
int ob_refcnt;
struct _typeobject *ob_type; /* type */
... an unknown amount of stuff used to represent the value ...
} MyObject;

In CPython, the MyObject* pointer is the identity.  The ob_refcnt field is a
CPython implementation detail.  The ob_type field contains the type.  The
rest of the structure is known only by the MyObject type implementation.

/F



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


Re: Placing graphics text on printed page - jan06call.jpg (0/1)

2006-01-13 Thread Paul Boddie
Steve Holden wrote:
 Michael Galvin wrote:
  To see an example of what I am trying to accomplish, look at this page
  on my personal website:
 
  http://mysite.verizon.net/michaelgalvin/jan06call.html
 
  I now realize my attachement could not be posted on this usenet group.
 
 I suspect your best option would be to use ReportLab's open source
 package (www.reportlab.org) to generate PDF files.

One alternative, although I'm not convinced that it is actively
maintained any more, is the Piddle/Sping library [1]. As mentioned
elsewhere, the Cairo bindings would provide a similar developer
experience to that, and Cairo is increasingly fashionable.

 You may, however, be able to get at the Windows device context through
 wxPython (www.wxpython.org): if you download the demonstration you'll
 see that on Windows they do send fairly arbitrary graphics to the
 Windows printer queue.

PyQt [2] seems to support printing fairly conveniently. Consider this
very simple example:

from qt import *
import sys
qapp = QApplication(sys.argv)
printer = QPrinter(QPrinter.PrinterResolution)
printer.setPageSize(printer.A4)
printer.setOutputToFile(1)
printer.setOutputFileName(qtprint.ps)
painter = QPainter(printer)
painter.drawText(painter.window(), painter.AlignCenter, Hello)
painter.end()

I haven't used printing in Qt [3] before, so apologies must go out if
I've made fundamental mistakes in the above code which did, admittedly,
produce output that resembled my expectations. Another route might be
to use a Tkinter canvas - at least in times of old, such canvases were
able to dump their contents as PostScript.

Paul

[1] http://piddle.sourceforge.net/
[2] http://www.riverbankcomputing.co.uk/pyqt/index.php
[3] http://doc.trolltech.com/3.3/graphics.html

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


Retrieve a GIF's palette entries using Python Imaging Library (PIL)

2006-01-13 Thread Stuart
I am using the Python Imaging Library (PIL) to process GIF images. I 
need to be able to retrieve the RGB values for each color palette entry.

I see that the 'Image' class has a 'palette' attribute which returns an 
object of type 'ImagePalette'.  However, the documentation is a bit 
lacking regarding how to maniuplate the ImagePalette class to retrieve 
the palette entries' RGB values.  Can anyone point me to a short example?

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


Re: Why is there no post-pre increment operator in python

2006-01-13 Thread Roy Smith
[EMAIL PROTECTED] wrote:
 Anyone has any idea on why is there no post/pre increment operators in
 python ?  

Short answer: Because Guido didn't like them.

Longer answer: Because they encourage people to write cryptic one-liners.  
There really isn't anything you can't write with them that you couldn't 
write just as well without them.  It just takes another line or two of 
code.  The end result may be a little longer, but it's almost always easier 
to understand.

 Although the statement:
 ++j
 works but does nothing

Well, it works in the sense that it's not a syntax error, but it doesn't 
quite do nothing.  It applies the unary + operator to the value of j, then 
does it again, then throws away the result.  Granted, that's probably not 
what you expected, and probably not very useful, but it's not quite 
nothing.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get Windows system information?

2006-01-13 Thread dpickles
Does anybody know how to get the:

 Free hard disk space
 Amount of CPU load
 and Amount of RAM used

on windows? I am making an artificial intelligence program that has
moods based on how much stress the system is under, based on these
parameters. I think it could possibly be done via COM. I am not looking
for a cross-platform solution- just something that will work on
Windows. Thank you for your help!

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


Re: Unicode style in win32/PythonWin

2006-01-13 Thread Robert

Thomas Heller schrieb:

 Robert [EMAIL PROTECTED] writes:

  Neil Hodgson wrote:
  Robert:
 
   After is_platform_unicode = auto, scintilla displays some unicode
   as you showed. but the win32-functions (e.g. MessageBox) still do not
   pass through wide unicode.
 
  Win32 issues are better discussed on the python-win32 mailing list
  which is read by more of the people interested in working on this library.
  http://mail.python.org/mailman/listinfo/python-win32
  Patches that improve MessageBox in particular or larger sets of
  functions in a general way are likely to be welcomed.
 
  ok. I have no patches so far as of now - maybe later. Played with
  Heller's ctypes for my urgent needs. That works correct with unicode
  like this:
 
  import ctypes
  ctypes.windll.user32.MessageBoxW(0,u'\u041f\u043e\u0448\u0443\u043a.txt',0,0)
  1

 FYI, if you assign the argtypes attribute for ctypes functions, the
 ascii/unicode conversion is automatic (if needed).

 So after these assignments:

   ctypes.windll.user32.MessageBoxW.argtypes = (c_int, c_wchar_p,
c_wchar_p, c_int)
   ctypes.windll.user32.MessageBoxA.argtypes = (c_int, c_char_p,
c_char_p, c_int)

 both MessageBoxA and MessageBoxW can both be called with either ansi and
 unicode strings, and should work correctly.  By default the conversion
 is done with ('msbc', 'ignore'), but this can also be changed,
 ctypes-wide, with a call to ctypes.set_conversion_mode(encoding,errors).

That is a right style of functionality, consistency and duty-free
default execution flow which python and pythonwin are lacking so far.
Those have no prominent mode-setting function, the mode-_tuple_ etc. so
far and/or defaults are set to break simple apps with common tasks.

Only question: is there a reason to have 'ignore' instead of 'replace'
as default? Wouldn't 'replace' deliver better indications (as for
example every Webbrowser does on unknown unicode chars ; (and even
mbcs_encode in 'strict'-mode) ). I can not see any advantage of
'ignore' vs. 'replace' when strict equality anyway has been given up
...

Robert

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


Re: Remote Function Call

2006-01-13 Thread Frithiof Andreas Jensen

Mike [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Hi,

 I have two machines. A python program on machine 1 needs to make a
 python call to a method in machine 2. What is the most efficient / fast

Some Custom Mechanism: Pyro or SPREAD f.ex.

 / programmer friendly way to do it?

XML-RPC - the client and server is already included in Python's standard
libraries!

The protocol is text-based so it is easy to generate test cases for each
component.


 - XML-RPC?
 - Http Call?

 Thanks,
 Mike



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


Converting a string to an array?

2006-01-13 Thread Tim Chase
While working on a Jumble-esque program, I was trying to get a 
string into a character array.  Unfortunately, it seems to choke 
on the following

import random
s = abcefg
random.shuffle(s)

returning

   File /usr/lib/python2.3/random.py, line 250, in shuffle
 x[i], x[j] = x[j], x[i]
   TypeError: object doesn't support item assignment

The closest hack I could come up with was

import random
s = abcdefg
a = []
a.extend(s)
random.shuffle(a)
s = .join(a)

This lacks the beauty of most python code, and clearly feels like 
there's somethign I'm missing.  Is there some method or function 
I've overlooked that would convert a string to an array with less 
song-and-dance?  Thanks,

-tim





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


Re: how do real python programmers work?

2006-01-13 Thread Ben Finney
Scott David Daniels [EMAIL PROTECTED] writes:
 bblais wrote:
 How do experienced python programmers usually do it?  Is there a
 usually about it, or is it up to personal taste?  Are there any
 convenient ways of doing these things?
 There are a lot of us who use a test-first process:
 Write a unit test, watch it fail, fix the code til the test passes.

I'm in this camp, but because I use Emacs I have an IDE:

  - multiple edit buffers for the Python code (any good editor can do
this)

  - from any Python code buffer, C-c C-c to execute

  - output shown in a new buffer, automatically jump to errors in code

  - separate buffer with a live Python prompt to experiment

  - separate buffer browsing documentation if needed

  - edit buffer for version control commit message

That's all a single Emacs session in one window of GNU screen; in a
separate window is a regular shell session where I can run other
things outside Emacs if I choose.

I'm currently using a version control system that doesn't integrate
with Emacs, so I have another shell buffer for that, plus an Emacs
buffer for the commit message. Ideally, I'd use Emacs native features
for version control too.

Another shell session constantly runs the project's unit tests (with a
'nice' setting so it doesn't get in the way of anything
process-intensive I might do elsewhere). I can quickly check the
pass/fail state of all the tests just by switching to that window.

All of the above could be done using many more screen sessions, but
Emacs buffers are more accessible when you're already editing.

-- 
 \  Time's fun when you're having flies.  -- Kermit the Frog |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string to datetime parser?

2006-01-13 Thread beza1e1
A good solution may be to specify a language to determine the order.
The default would be (something like) en-US and thus early October in
the example.

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


Re: how do real python programmers work?

2006-01-13 Thread Mike Meyer
bblais [EMAIL PROTECTED] writes:
 In Python, there seems to be a couple ways of doing things.   I could
 write it in one window, and from a Unix shell call
python myscript.py
 and be like C++, but then I lose the interactiveness which makes
 prototyping easier.  If I use the python shell, I can use import (and
 reload), or execfile perhaps.

 How do experienced python programmers usually do it?

I do it both ways - and at least one other. If I'm working on code
that's largely independent of the module, I'll use python-mode's
execute commands to send the code to the Python interpreter. If the
code needs the rest of the module, I'll use reload in the interactive
interpreter. In the final stages of module development, I'll have a
test at the end of the module, and switch to the shell to run the
module as a script for testing.

Of course, a lot of what I do is web apps, so the later stages of
testing involve activating a browser and hitting reload.

  Is there a usually about it, or is it up to personal taste?  Are
 there any convenient ways of doing these things?

I think you've found some of the most convenient ones already. Maybe
some of the people who IDEs (instead of - well, we need a term for
development environment built out of Unix tools) will let us know
what they do.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to an array?

2006-01-13 Thread Bryan Olson
Tim Chase wrote:
 While working on a Jumble-esque program, I was trying to get a string 
 into a character array.  Unfortunately, it seems to choke on the following
 
 import random
 s = abcefg
 random.shuffle(s)
 
 returning
 
   File /usr/lib/python2.3/random.py, line 250, in shuffle
 x[i], x[j] = x[j], x[i]
   TypeError: object doesn't support item assignment

Yes, Python has had that same problem elsewhere, notably the
mutating methods 'sort' and 'reverse'. Those problems are now
reasonably well solved. What's really neat is that the names
of the new methods: 'sorted' and 'reversed', are adjectives
describing the return values we want, where 'sort' and
'reverse' are verbs, calling for procedures to be performed.


For sorting, we had the procedure 'sort', then added the pure
function 'sorted'. We had a 'reverse' procedure, and wisely
added the 'reversed' function.

Hmmm... what we could we possible do about 'shuffle'?


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


Re: gracefully handling broken pipes (was Re: Converting a string toan array?)

2006-01-13 Thread Fredrik Lundh
Tim Chase wrote:

import random
s = abcdefg
data = list(s)
random.shuffle(data)
.join(data)
  'bfegacd'
 
  fit you better?

 Excellent!  Thanks.  I kept trying to find something like an
 array() function.  Too many languages, too little depth.

 from array import array
 a = array('c', abcdefgh)
 a
array('c', 'abcdefgh')
 import random
 random.shuffle(a)
 a
array('c', 'gfecdabh')
 a.tostring()
'gfecdabh'

/F



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


Re: how do real python programmers work?

2006-01-13 Thread Scott David Daniels
bblais wrote:
 How do experienced python programmers usually do it?  Is there a
 usually about it, or is it up to personal taste?  Are there any
 convenient ways of doing these things?
There are a lot of us who use a test-first process:
Write a unit test, watch it fail, fix the code til the test passes.
If the project is smallish, I'll have Idle to experiment a bit (as
others have said, for checking boundary cases on standard module
functions).

So:
window A: test file editor
window B: module editor
window C: command line for running tests.
window D: idle for checking boundary conditions on Python modules.

My typical cycle is change file (either window A or B), save that,
re-run the unit test in window C.  Every now and then (when test are
succeeding), I check in the sources (and the tests).  Before I was
doing this, I explored my module with Idle, but that often left me
with too few test cases.


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with super()

2006-01-13 Thread Paul McNett
David Hirschfield wrote:
 So, the larger question is how to do anything that resembles what I 
 want, which is to have a chain of subclasses with a single attribute 
 that each subclass can define as it wishes to, but with the ability to 
 get the combined value from all the ancestors down to the current 
 subclass I access that attribute from.
 
 Does that make any sense?

Yes, it makes sense. The trick is to not query the values using self, but to 
ask 
the class definitions for the attribute. See my second message that gives an 
example, climbing the __mro__ tree backwards.


-- 
Paul McNett
http://paulmcnett.com
http://dabodev.com

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


Re: another docs problem - imp

2006-01-13 Thread rurpy
Fredrik Lundh [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 [EMAIL PROTECTED] wrote:

   from the find_module documentation:
  
 find_module( name[, path])
  
   Try to find the module _name_ on the search path _path_.
   If _path_ is a list of directory names, each directory is
   searched for files /.../. Invalid names in the list are
   silently ignored (but all list items must be strings).
   If _path_ is omitted or None, the list of directory names
   given by _sys.path_ is searched /.../
  
   it's not obvious how anyone can interpret the alternatives a
   list where all items are strings / omitted / None as not a hint
   that a list is expected and a single string *should* work (i.e.
   be treated as a pathname, rather than a sequence).
 
  Well, I interpreted the if's as describing special cases
  addtional to the first sentence.

 The first sentence says that the _path_ argument is a search path.
 It does not say that it can be a string; that's something you made
 up all by yourself.

Correct it does not say it's a string.  But your implication that
one can therefore conclude that it is not a string is silly.
From unittest:
 assert_( expr[, msg])
 failUnless( expr[, msg])
 Signal a test failure if expr is false; the explanation for the error
 will be msg if given, otherwise it will be None.
I should conclude that msg is not a string because
it doesn't say it is a string?

  May I suggest that the problem is easily fixed simply
  by removing the first if.

 Like

 Try to find the module _name_ on the search path _path_.
 _path_ is a list of directory names, each directory is searched
 for files.

 ?  So what happens when pupry reads this, and gets annoyed that he
 always has to pass in a list ?  It's probably better if you learn to read
 technical documentation a bit more carefully.

Reading more carefully is always useful.  But that does
not remove the obligation of the writer to write clearly and
unambiguously.  Why would pupry think s/he always has
to pass in a list when the syntax description clearly shows
the arument is optional, and the following if sentence states
it is optional?  But perhaps you are right; perhaps something
like _path_is a optional list of... would be clearer.

 ... and don't give me any you're defending the status quo crap in
 response to this.  There are lots of things to do in the library reference,
 and a few of us are working on it (using different approaches), but
 trust me, optimizing for a few

optimize: to make as perfect, effective, or functional as possible.
(Merriam Webster New Collegiate)

few has nothing to do with it.
If this required a huge amount of work, your resistance
would be understandable.  Since the wording changes
are petty minor your flamage over this is puzzling.

 1 - I think I know how this works
Wrong, I had no idea how it worked and read the docs
first.
 2 - oh, it didn't work.  let's check the documentation
Yes, read it a second time, didn't see the alternate interpretation.
 3 - I think I've found a way to interpret the documentation as if
 it allows me to do what I'm doing.  it doesn't explicitly say that
 I can do this, but it doesn't explicitly rule it out either, so I'm
 probably right.  I'll try again.  maybe it works this time.
Nope.  It was hmm, seems to clearly state that it
takes a path argument.  Since I was dealing with a
single directory, and (this stuff dealing with imports
and all) had just before been thinking about sys.path
solutions, I was primed to accept that the argument
was a string and assumed I must be doing something
wrong.  later Is there any source?  Nope
must be C. later How about google.  Oh here
is someone with same problem, Damn, no answer.
Ohh here is some one else, different problem but
he tried both find_module(..,xxx) and (..,[xxx])
and the latter didn't generate the error message.
 4 - (2 hours later) maybe I should try one of the alternatives that
 is mentioned in the documentation.  oh, it did work if I follow the
 instructions.  now I'm REALLY pissed, and am going to spend
 another hour arguing about this on the internet.
No.  As I said, I did not see your way of interpreting the
documentation until you posted.  And I had no plans
to argue about it.  I posted for the reasons I gave,
and made a suggestion about how the documention
could be improved.
Well, in your attempt at mind reading you at least
got one out of four.

 practitioners, over the
 1 - I think I know how this works
 2 - oh, it didn't work.  let's check the documentation.
 3 - it says can be a list or can be omitted.  let's try one of
 those.  oh, it worked.

How about
1 - read some clear unambiguous documentation.
2 - write the code and it works as described.

My grandfather used to own a hardware store.
He frequently said he took every customer
complaint very seriously.  For every customer
who 

Re: Why is there no post-pre increment operator in python

2006-01-13 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
 Anyone has any idea on why is there no post/pre increment operators in
 python ?  
 Although the statement:
 ++j
 works but does nothing

The reason is pretty complex, but here it is:  Python is not C.

-Peter

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


Re: How can I make a dictionary that marks itself when it's modified?

2006-01-13 Thread Christian Tismer
Just to add a word that I forgot:

Adhering to the subject line, the intent is to track modifications
of a dict.
By definition, modification of a member of a dict without replacing
the value is not considered a dict change.

I'd stick with the shallow approach.
Asking to track mutation of an element in the general case
is causing much trouble.
Support for element tracking can probably provided by overriding
the dict's getattr and recording the element in some extra
candidate list.
If the element itself is modified, it then could be looked up
as a member of that dict, given that the element's setattr
is traced, too.

ciao - chris

-- 
Christian Tismer :^)   mailto:[EMAIL PROTECTED]
tismerysoft GmbH : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9A :*Starship* http://starship.python.net/
14109 Berlin : PGP key - http://wwwkeys.pgp.net/
work +49 30 802 86 56  mobile +49 173 24 18 776  fax +49 30 80 90 57 05
PGP 0x57F3BF04   9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
  whom do you want to sponsor today?   http://www.stackless.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: another docs problem - imp

2006-01-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

  The first sentence says that the _path_ argument is a search path.
  It does not say that it can be a string; that's something you made
  up all by yourself.

 Correct it does not say it's a string.  But your implication that
 one can therefore conclude that it is not a string is silly.

 From unittest:
  assert_( expr[, msg])
  failUnless( expr[, msg])
  Signal a test failure if expr is false; the explanation for the error
  will be msg if given, otherwise it will be None.

 I should conclude that msg is not a string because
 it doesn't say it is a string?

nice logic, there.

/F



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


Re: Limiting the size of List and making it Homogeneous

2006-01-13 Thread bearophileHUGS
The array module allows you to specify a single type of elements.

Bye,
bearophile

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


Re: atexit + threads = bug?

2006-01-13 Thread David Rushby
[Tim Peters]
 [David Rushby]
 They say, Functions thus registered are automatically executed upon
 normal interpreter termination.  It seems like sophistry to argue that
 normal interpreter termination has occurred when there are still
 threads other than the main thread running.

 Well, since atexit callbacks are written in Python, it's absurd on the
 face of it to imagine that they run after the interpreter has torn
 itself down.

Of course.

 It's also strained to imagine that threads have nothing to do
 with shutdown...

I don't imagine that.

 You're welcome to suggest text you'd like better...

What I'd like is for the behavior to become less surprising, so that
the text could describe reasonable behavior, instead of retrofitting
the text to more clearly explain (what I regard as) flawed behavior.

What would be unreasonable about adding a
  join_nondaemonic_threads()
call before the call to
  call_sys_exitfunc()
near the beginning of Py_Finalize?

Instead of _MainThread.__exitfunc having to rely on atexit.register to
ensure that it gets called, join_nondaemonic_threads would call
_MainThread.__exitfunc (or some functional equivalent).  Both
join_nondaemonic_threads and call_sys_exitfunc would execute while the
interpreter is still entirely intact, as the Py_Finalize comment
says.

The opening paragraph of the atexit docs could then read:
The atexit module defines a single function to register cleanup
functions. Functions thus registered are automatically executed when
the main thread begins the process of tearing down the interpreter,
which occurs after all other non-daemonic threads have terminated and
the main thread has nothing but cleanup code left to execute.

This seems simple.  Am I overlooking something?

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


Re: how do real python programmers work?

2006-01-13 Thread Travis E. Oliphant
bblais wrote:
 In Python, there seems to be a couple ways of doing things.   I could
 write it in one window, and from a Unix shell call
python myscript.py
 and be like C++, but then I lose the interactiveness which makes
 prototyping easier.  If I use the python shell, I can use import (and
 reload), or execfile perhaps.

Try IPython.  It makes the process of executing live code very productive.

http://ipython.scipy.org

-Travis

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


Re: How to remove subset from a file efficiently?

2006-01-13 Thread Christopher Weimann
On 01/12/2006-09:04AM, fynali wrote:
 
   - PSP320.dat (quite a large list of mobile numbers),
   - CBR319.dat (a subset of the above, a list of barred bumbers)
 

fgrep -x -v -f CBR319.dat PSP320.dat  PSP-CBR.dat

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


Re: how do real python programmers work?

2006-01-13 Thread Tom Anderson
On Thu, 12 Jan 2006, bblais wrote:

 In Matlab, I do much the same thing, except there is no compile phase. I 
 have the editor on one window, the Matlab interactive shell in the 
 other.  I often make a bunch of small scripts for exploration of a 
 problem, before writing any larger apps.  I go back and forth editing 
 the current file, and then running it directly (Matlab looks at the time 
 stamp, and automagically reloads the script when I modify it).

I wouldn't describe myself as an experienced programmer, but this is 
definitely how i work - editor plus interactive interpreter, using 
import/reload to bring in and play with bits of of code.

Towards the end of coding a program, when i'm done with the inner 
functions and am working on the main function, which does stuff like 
command line parsing, setting up input and output, etc, i'll often leave 
the interpreter and work from the OS shell, since that's the proper 
environment for a whole program.

Often, i'll actually have more than one shell open - generally three: one 
with an interpreter without my code loaded, for doing general exploratory 
programming, testing code fragments, doing sums, etc; one with an 
interpreter with my code loaded, for testing individual components of the 
code, and one at the OS shell, for doing whole-program tests, firing up 
editors, general shell work, etc.

Another trick is to write lightweight tests as functions in the 
interpreter-with-code-loaded that reload my module and then do something 
with it. For example, for testing my (entirely fictional) video 
compressor, i might write:

def testcompressor():
reload(vidzip)
seq = vidzip.ImageSequence((640, 480))
for i in xrange(200):
frameName = testmovie.%02i.png % i
frame = Image.open(frameName)
seq.append(frame)
codec = vidzip.Compressor(vidzip.DIRAC, 9)
codec.compress(seq, file(testmovie.bbc, w))

Then, after editing and saving my code, i can just enter 
testcompressor() (or, in most cases, hit up-arrow and return) to reload 
and test. You can obviously extend this a bit to make the test routine 
take parameters which control the nature of the test, so you can easily 
test a range of things, and you can have multiple different test on the go 
at once.

tom

-- 
Only men's minds could have mapped into abstraction such a territory
-- 
http://mail.python.org/mailman/listinfo/python-list


gracefully handling broken pipes (was Re: Converting a string to an array?)

2006-01-13 Thread Tim Chase
   import random
   s = abcdefg
   data = list(s)
   random.shuffle(data)
   .join(data)
 'bfegacd'
 
 fit you better?

Excellent!  Thanks.  I kept trying to find something like an 
array() function.  Too many languages, too little depth.

The program was just a short script to scramble the insides of 
words to exercise word recognition, even when the word is mangled.

It's amazing how little code it takes to get this working.

When using it as a filter, if a downstream pipe (such as head) 
cuts it off, I get an error:

bash# ./scramble.py bigfile.txt | head -50

[proper output here]

Traceback (most recent call last):
  File ./scramble.py, line 11, in ?
print r.sub(shuffleWord, line),
IOError: [Errno 32] Broken pipe

At the moment, I'm just wrapping the lot in a try/except block, 
and ignoring the error.  Is there a better way to deal with this 
gracefully?  If some more serious IO error occurred, it would be 
nice to not throw that baby out with the bath-water.  Is there a 
way to discern a broken pipe from other IOError exceptions?

Thanks again.

-tim

import random, sys, re
r = re.compile([A-Za-z][a-z]{3,})
def shuffleWord(matchobj):
 s = matchobj.group(0)
 a = list(s[1:-1])
 random.shuffle(a)
 return .join([s[0], .join(a), s[-1]])
try:
 for line in sys.stdin.readlines():
 print r.sub(shuffleWord, line),
except IOError:
 pass




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


Re: How to remove subset from a file efficiently?

2006-01-13 Thread fynali
The code it down to 5 lines!

#!/usr/bin/python

barred = set(open('/home/sajid/python/wip/CBR319.dat'))

postpaid_file = open('/home/sajid/python/wip/PSP320.dat')
outfile = open('/home/sajid/python/wip/PSP-CBR.dat', 'w')

outfile.writelines(number for number in postpaid_file if number not
in barred)

postpaid_file.close(); outfile.close()

Awesome! (-:  Thanks a ton Fredrik, Steve.

$ time ./cleanup.py

real0m11.048s
user0m5.232s
sys 0m0.584s

But there seem to be that discrepancy; will chk and update back here.

Thank you all once again.

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


Re: How to remove subset from a file efficiently?

2006-01-13 Thread Steve Holden
Fredrik Lundh wrote:
 Steve Holden wrote:
 
 
looks like premature non-optimization to me...


It might be quicker to establish a dict whose keys are the barred
numbers and use that, rather than a list, to determine whether the input
numbers should make it through.
 
 
 what do you think
 
 
barred = set(open('/home/sjd/python/wip/CBR319.dat'))
 
 
 does ? ;-)
 
:-}

Duh.
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Remote Function Call

2006-01-13 Thread Mike
Hi,

I have two machines. A python program on machine 1 needs to make a
python call to a method in machine 2. What is the most efficient / fast
/ programmer friendly way to do it?

- XML-RPC?
- Http Call?

Thanks,
Mike

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


Re: how do real python programmers work?

2006-01-13 Thread Juho Schultz
bblais wrote:

 In Python, there seems to be a couple ways of doing things.   I could
 write it in one window, and from a Unix shell call
python myscript.py
 and be like C++, but then I lose the interactiveness which makes
 prototyping easier.  If I use the python shell, I can use import (and
 reload), or execfile perhaps.
 
 How do experienced python programmers usually do it?  Is there a
 usually about it, or is it up to personal taste?  Are there any
 convenient ways of doing these things?
 

Disclaimer: I do not consider myself an experienced python programmer.

For scripts and small programs (one file, one developer) I use emacs and 
python shell. For larger projects I use Eclipse and pydev.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do real python programmers work?

2006-01-13 Thread Michele Simionato
As many others, I use emacs for programming and ipython for interactive
experiments.

  Michele Simionato

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


Re: how do real python programmers work?

2006-01-13 Thread bruno at modulix
bblais wrote:
 Hello,
 
(snip)
 
 In C++, I open up an editor in one window, a Unix shell in another. 
(snip)
 In Matlab, I do much the same thing, except there is no compile phase.
(snip)
 In Python, there seems to be a couple ways of doing things.   I could
 write it in one window, and from a Unix shell call
python myscript.py
 and be like C++, but then I lose the interactiveness which makes
 prototyping easier.  If I use the python shell, I can use import (and
 reload), or execfile perhaps.

 How do experienced python programmers usually do it?  

I'm not sure I qualify as a experienced, but...

 Is there a
 usually about it, or is it up to personal taste? 

Mostly. There's no shortage of Python IDE/editors/...

 Are there any
 convenient ways of doing these things?

my-2-cents
Try emacs + python-mode. It offers the best editor/interactive shell
I've ever seen.
/my-2-cents

-- 
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: Remote Function Call

2006-01-13 Thread david mugnai
On Thu, 12 Jan 2006 18:29:50 -0800, Mike wrote:

 Sounds like what I need. Thanks Irmen. I heard google uses python with
please look carefully at this page:
http://pyro.sourceforge.net/manual/9-security.html

particulary:
http://pyro.sourceforge.net/manual/9-security.html#pickle

another option is to use Perspective Broker from the Twisted Matrix
framework

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


Re: [OT] how do real python programmers work?

2006-01-13 Thread bruno at modulix
Mike Meyer wrote:
(snip)
 Maybe
 some of the people who IDEs (instead of - well, we need a term for
 development environment built out of Unix tools) 

Extegrated Development environment ?-)

-- 
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: flatten a level one list

2006-01-13 Thread Nick Craig-Wood
Alex Martelli [EMAIL PROTECTED] wrote:
  Nick Craig-Wood [EMAIL PROTECTED] wrote:
  Except if you are trying to sum arrays of strings...
  
 sum([a,b,c], )
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
 
  
  I've no idea why this limitation is here... perhaps it is because pre
  python2.4 calling += on strings was very slow?
 
  No: when I implemented sum, I originally specialcased sum on strings to
  map down to a ''.join -- Guido decided it was confusing and had no
  advantage wrt calling ''.join directly so he made me put in that
  check.

Hmm, interesting...

I agree with Guido about the special case, but I disagree about the
error message.  Not being able to use sum(L,) reduces the
orthogonality of sum for no good reason I could see.

However I only noticed that when trying to do the recent python
challenge which probaby isn't the best use case ;-)

-- 
Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Conditionals stored as text to translate to real compares

2006-01-13 Thread Randall Parker
I want to know if there is some way to translate fragments of text into
operators (e.g. , , , ==, etc) to use in conditional expressions.

I've got a data structure which is a list of lists. A single list might
look like:

MyInnerList = [MyVar,,7]
or
MySecondInnerList = [MyOtherVar,=,25.5]

These all go in something like:
MyMainList = [[MyVar,,7],[MyOtherVar,=,25.5], and so on...]

I have some target device which I go query with the names in the first
field (e.g. MyVar) to get values back. The target device returns all
values as strings. Then I want to compare to the value in the third
field.

In theory the third field might contain floats, integers, or maybe some
day strings.

So I access the middle operator field like this:

OperatorType = MyInnerList[1] # This gets back  or = for example
TestVal = MyInnerList(2)
TargetVal gets filled in by talking to my target device.

Then I want to compare TestVal and TargetVal using OperatorType.

I'm thinking I have to do something like:

if OperatorType == :
   # then do a greater than compare here.
   BoolVal = TestVal  TargetVal
elif OperatorType == =:
   # then do a greater or equal to here.
   BoolVal = TestVal = TargetVal
 and so on.

It would seem a lot easier to do:

BoolVal  = TargetVal EvalStrToOper() MyInnerList(2)

 where EvalStrToOper creates an immediate  sign that then allows that
line to get evaluated by the interpreter.

Is there any way to do that in Python?

Of course, I'd have to guarantee that the  or other operators are
really legal operators. Also, I'd have to test MyInnerList(2) to make
sure it is an appropriate type.

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


Re: - E04 - Leadership! Google, Guido van Rossum, PSF

2006-01-13 Thread Aahz
In article [EMAIL PROTECTED],
Dave Hansen  [EMAIL PROTECTED] wrote:

And, FWIW, I don't think I could convince my wife (or myself) to move
to CullyFORNya for any amount of money, whether there was a massage
therapist on duty or not...

Google also has technical offices in the New York area.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

19. A language that doesn't affect the way you think about programming,
is not worth knowing.  --Alan Perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for a particular http proxy...

2006-01-13 Thread Fred Pacquier
Hello,

I would be grateful if someone could point me to an existing and working 
http proxy implementation that satisfies the following requirements :

- as small and simple as possible, ideally no dependencies outside python
- easy to customize (for controlling outgoing http headers for instance)
- supports chaining to another remote proxy

I have spent some time on the list at : 
http://xhaus.com/alan/python/proxies.html

...but haven't found what I need yet : Some old pages/packages have broken 
links ; some are too full-featured and/or have heavy dependencies (xml, 
ssl, twisted etc.) ; some have remote proxy support but are complicated 
enough that I'm not sure where to hack at the request headers ; and the 
really simple ones don't chain to other proxies.

Actually Tiny HTTP Proxy and its derivatives would be just fine for what 
I want to do, but I don't know how and where to add remote proxy support.
I did get httpMonitor to work (although it is overkill), but it depends on 
PyXML (still 900 KB even pared down some), and it seems to have some 
strange side effects on the browser.

Any ideas welcome,
TIA,
fp

-- 
YAFAP : http://www.multimania.com/fredp/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: void * C array to a Numpy array using Swig

2006-01-13 Thread Travis E. Oliphant
Krish wrote:
 Hello People
 
 I hope I am On Topic. Anyways, here is my problem. Any insights would
 be really appreciated.

Posting to the [EMAIL PROTECTED]  list would help 
generate more responses, I think.

 
 I have wrapped a C IO module using SWIG - Python Module. Suppose the
 name of the module is imageio and the reader function from the file
 is image_read() which returns an object ( filled C structure) with a
 lot of members.
 
 Let
 
 a = imageio.image_read(testfile.image)
 
 Now a is the object which contains pointer to data of the image. ( void
 * pdata). ( a also contains the datatype which I need to typecast to
 get the data pointed by pdata). My question is how to access the data
 pointed by pdata in *Python*.

Yes, you are right that you need to use typemaps.  It's been awhile 
since I did this kind of thing, but here are some pointers.

1)  Look at Michael Sanner's typemaps at

http://www.scripps.edu/mb/olson/people/sanner/html/Python/NumericTypemaps/

Except for the CHAR version, these should work for NumPy by replacing 
Numeric/arrayobject.h with numpy/arrayobject.h

2) In full scipy there are typemaps for numpy arrays in 
cluster/src/swig_num.i

Look here...

http://projects.scipy.org/scipy/scipy/file/trunk/Lib/cluster/src/swig_num.i

This should help you get started with some examples.  Typemaps can be a 
little confusing at first, but they do make your interface a bit nicer.

-Travis

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


Re: how do real python programmers work?

2006-01-13 Thread Fuzzyman

bblais wrote:
[snip..]
 In Python, there seems to be a couple ways of doing things.   I could
 write it in one window, and from a Unix shell call
python myscript.py
 and be like C++, but then I lose the interactiveness which makes
 prototyping easier.  If I use the python shell, I can use import (and
 reload), or execfile perhaps.

 How do experienced python programmers usually do it?  Is there a
 usually about it, or is it up to personal taste?  Are there any
 convenient ways of doing these things?

 I realize this is a pretty newbie question, but it could possibly save
 me hours of time if there is a better way to work.


SPE (the IDE) has several nice ways of running code - including
launching it as an external file.

This is what I use for almost all my development.

All the best,

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


 
   thanks,
 
 Brian Blais

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


Re: Ann: Tkinter drag and drop module

2006-01-13 Thread tim





  
The module can be used with both standard Tkinter and Tix, and makes it
quite easy to e.g. drop a bunch of files from a file manager onto any
Tkinter widget.
It comes with a basic reference manual and a small demo app.
It can be found at
http://www.8ung.at/klappnase/TkinterDnD/TkinterDnD.html.

Any feedback is much appreciated.

Best regards

Michael

  


Hi Michael and list,

I tried to run dnddemo.py (win XP, Python2.4).

but get:

 File "C:\Documents and
Settings\Tim\Bureaublad\installes_pc_mac\programming\python\TkinterDnD-0.4\TkinterDnD\TkinterDnD.py",
line 333, in _require
 tkdndver = tkroot.tk.call('package', 'require', 'tkdnd')
TclError: can't find package tkdnd

Probably something went wrong installing tkdnd.
I got the libtkdnd10.dll from
http://mirror.optusnet.com.au/sourceforge/t/tk/tkdnd/ but am not so
sure where to put it.
The installation section on
http://www.iit.demokritos.gr/~petasis/Tcl/tkDND/tkDND.html

'If your platform is Microsoft Windows, then allong with the
distribution
there is a stubs enabled dynamic library (dll) that was built
against tk8.4a1, with the use of VC++ 5.0. If you cannot use the
provided
binary, then you can always create the required library by using the
VC++
project files located in the "win" directory of the tkDND distribution.
In all other cases, you should create the library only from the files
located in the directories "win" (*.cpp *.h) and "generic" (*.c *.h).
You will need a C++ compiler for this.'

wasn't very helpful for me.

Maybe someone can give me a simple howto for installing this?

thank you,
Tim



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

Re: Real-world use cases for map's None fill-in feature?

2006-01-13 Thread rurpy
Raymond Hettinger [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED]
How well correlated in the use of map()-with-fill with the
(need for) the use of zip/izip-with-fill?

 [raymond]
   Close to 100%.  A non-iterator version of izip_longest() is exactly
   equivalent to map(None, it1, it2, ...).

 [EMAIL PROTECTED]
  If I use map()
  I can trivially determine the arguments lengths and deal with
  unequal length before map().  With iterators that is more
  difficult.  So I can imagine many cases where izip might
  be applicable but map not, and a lack of map use cases
  not representative of izip use cases.

 You don't seem to understand what map() does.  There is no need  to
 deal with unequal argument lengths before map(); it does the work for
 you.  It handles iterator inputs the same way.  Meditate on this:

 def izip_longest(*args):
 return iter(map(None, *args))

 Modulo arbitrary fill values and lazily evaluated inputs, the semantics
 are exactly what is being requested.  Ergo, lack of use cases for
 map(None,it1,it2) means that izip_longest(it1,it2) isn't needed.

lazily evaluated inputs is exactly what I was pointing
out and what make your izip_longest() above not the
same as map(None,...), and hence, your conclusion
invalid.  Specifically

def izip_longest(*args):
return iter(map(None, *args))
f1 = file (test.dat)
f2 = file (test.dat)
it = izip2 (f1, f2)
while 1:
h1, h2 = it.next ()
print h1.strip(), h2

izip2() in the above code is a real izip_longest
based on a version posted in this thread.

 test.py
3347 3347
-3487 -3487
2011 2011
239 239
...

Replace izip2 in the above code with your izip_longest
 test.py
[wait, wait, wait,... after a few minutes type ^c, nothing
happens, close window].

I don't think your izip_longest is at all equivalent to
the proposed izip, and thus there may well be uses
cases for izip that aren't represented by imap(None,...)
use cases, which is what I said.  That is, I might have
a use case for izip which I would never even consider
map() for.

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


Re: New Python.org website ?

2006-01-13 Thread Fuzzyman

Tim Parkin wrote:
[snip..]
 Hi Fuzzyman,

 Thanks for the feedback and volunteering to contribue... The list of
 already built sections is not really up to date but I have added a few
 tickets to the trac on some sections of content that need working on. If

Great - can you provide a URL please ?

I had a browse through the tickets, and dumb old me couldn';t find
them.

I'd be well pleased to be able to help.

Thanks

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

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


Re: Creating shortcuts?

2006-01-13 Thread Roger Upole
On Windows, Pywin32 allows you to create and manipulate
shortcuts.  See \win32comext\shell\test\link.py for a small
class that wraps the required interfaces.
hth
Roger

Ron Griswold [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]
Hi Folks,

Is it possible to create a shortcut to a file in Python? I need to do
this in both win32 and OSX. I've already got it covered in Linux by
system(ln...).

Thanks,

Ron Griswold
Character TD
R!OT Pictures
[EMAIL PROTECTED]



== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with super()

2006-01-13 Thread Mike Meyer
David Hirschfield [EMAIL PROTECTED] writes:
 I'm having trouble with the new descriptor-based mechanisms like
 super() and property() stemming, most likely, from my lack of
 knowledge about how they work.

 Here's an example that's giving me trouble, I know it won't work, but
 it illustrates what I want to do:

 class A(object):
 _v = [1,2,3]
  def _getv(self):
 if self.__class__ == A:
 return self._v
 return super(self.__class__,self).v + self._v

 v = property(_getv)


 class B(A):
 _v = [4,5,6]
b = B()
 print b.v

 What I want is for b.v to give me back [1,2,3,4,5,6], but this example
 gets into a recursive infinite loop, since super(B,self).v is still
 B._getv(), not A._getv().

 Is there a way to get what I'm after using super()?

Yes. Call super with A as the first argument, not self.__class__.

That's twice in the last little bit I've seen someone incorrectly use
self.__class__ instead of using the class name. Is there bogus
documentation somewhere that's recommending this?

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I make a dictionary that marks itself when it's modified?

2006-01-13 Thread Christian Tismer
Steve Holden wrote:
 Christian Tismer wrote:
 Just to add a word that I forgot:

 Adhering to the subject line, the intent is to track modifications
 of a dict.
 By definition, modification of a member of a dict without replacing
 the value is not considered a dict change.

 Well, I agree. But I suppose much depends on exactly what the OP meant 
 by ... add a new element or alter an existing one. The post did follow 
 that with (the values in the dict are mutable), which is presumably 
 why garabik-2500 proposed catching __getitem__ as well as __setitem__.

Yes, I understood this after reading more. Probably easier to
solve if the problem is spelled more specifically.

 I merely wanted to point out (not to you!) that there was no effective 
 way to capture a change to a mutable item without, as you say, modifying 
 the element classes.

You are completely right. This is asking for too much, unless one is
prepared to heavily modify the interpreter for debugging purposes,
which actually might be a way to solve the specific problem, once.

cheers - chris

-- 
Christian Tismer :^)   mailto:[EMAIL PROTECTED]
tismerysoft GmbH : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9A :*Starship* http://starship.python.net/
14109 Berlin : PGP key - http://wwwkeys.pgp.net/
work +49 30 802 86 56  mobile +49 173 24 18 776  fax +49 30 80 90 57 05
PGP 0x57F3BF04   9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
  whom do you want to sponsor today?   http://www.stackless.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I make a dictionary that marks itself when it's modified?

2006-01-13 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 Thanks to everyone who posted comments or put some thought into this
 problem.
 
 I should have been more specific with what I want to do, from your
 comments the general case of this problem, while I hate to say
 impossible, is way more trouble than it's worth.
 
 By modified I meant that the dictionary has been changed from its
 original (constructed) state by either:
 1) A new element was added
 2) An existing element was changed
 
 I want to wrap a dictionary of cookies in mod_python. Cookies are
 represented as objects with no methods. In light of this and Michael's
 excellent post, I came up with the following code.
 
 class CookieCollection(dict):
def __init__(self, d):
   for k, v in d:
  v.__setattr__ = self.__wrap_setattr(v.__setattr__)
  self[k] = v

I don't think this will work if v is an instance of a new-style class - 
for new-style classes, special methods are always looked up on the 
class, you can't override them in an instance. For example:

   class foo(object):
  ...   def __setattr__(self, attr, value):
  ... print 'foo.__setattr__'
  ... object.__setattr__(self, attr, value)
  ...
   f=foo()
   f.x = 3
foo.__setattr__
   def new_setattr(attr, value):
  ...   print 'new_setattr'
  ...
   f.__setattr__ = new_setattr
foo.__setattr__
   f.y=3
foo.__setattr__

still calls foo.__setattr__()

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


Re: Help with super()

2006-01-13 Thread David Hirschfield
I tried that and super(B,self), but neither works.

Using super(A,self) in the _getv(self) method doesn't work, since the 
super() of A is object and that doesn't have the v property at all.
Not sure why you say that using self.__class__ is wrong as the first 
argument to super(), it should be the same as using the class name 
itself - both will result in class blah.B or whetever self is an 
instance of.

I still don't see a way to accomplish my original goal, but any other 
suggestions you might have would be appreciated.
Thanks,
-David

Mike Meyer wrote:

David Hirschfield [EMAIL PROTECTED] writes:
  

I'm having trouble with the new descriptor-based mechanisms like
super() and property() stemming, most likely, from my lack of
knowledge about how they work.

Here's an example that's giving me trouble, I know it won't work, but
it illustrates what I want to do:

class A(object):
_v = [1,2,3]
 def _getv(self):
if self.__class__ == A:
return self._v
return super(self.__class__,self).v + self._v

v = property(_getv)
   

class B(A):
_v = [4,5,6]
   b = B()
print b.v

What I want is for b.v to give me back [1,2,3,4,5,6], but this example
gets into a recursive infinite loop, since super(B,self).v is still
B._getv(), not A._getv().

Is there a way to get what I'm after using super()?



Yes. Call super with A as the first argument, not self.__class__.

That's twice in the last little bit I've seen someone incorrectly use
self.__class__ instead of using the class name. Is there bogus
documentation somewhere that's recommending this?

  mike
  


-- 
Presenting:
mediocre nebula.

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


Re: how do real python programmers work?

2006-01-13 Thread Carl Friedrich Bolz
Scott David Daniels wrote:
 bblais wrote:
 
How do experienced python programmers usually do it?  Is there a
usually about it, or is it up to personal taste?  Are there any
convenient ways of doing these things?
 
 There are a lot of us who use a test-first process:
 Write a unit test, watch it fail, fix the code til the test passes.

I second that. This is pretty much how I work (and almost all the other 
people in the PyPy project seem to have a similar strategy). First write 
a minimal test (with the py.test framework in the PyPy case). Then run 
it to see it fail which is important because it is easy to write a test 
that does not really test anything. Then do the least possible amount of 
work to make the test pass. I use konsole with one tab with vim and 
another tab where I run py.test, but that is a matter of taste. If the 
test fails although I think it should work I use the py.test 
pdb-feature, which lets you start pdb within the context of the failing 
test. When the test finally passes, I check it and the new code in. 
Rinse and repeat.

Cheers,

Carl Friedrich

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


Re: Unicode Pythonwin / win32 / console?

2006-01-13 Thread Martin v. Löwis
Robert wrote:
 * Webbrowsers for example have to display defective HTML as good as
 possible, unknown unicode chars as ? and so on... Users got very
 angry in the beginning of browsers when 'strict' programmers displayed
 their exception error boxes ...

Right. If you would develop a webbrowser in Python, you should do the
same.

 No one is really angry when
 occasionally chinese chars are displayed cryptically on non-chinese
 computers.

That is not true. Japanese are *frequently* upset when their
characters don't render correctly. They even have a word for that:
moji-bake. I assume it is the similar for Chinese.

 * anything is nice-printable in python by default, why not
 unicode-strings!? If the decision for default 'strict' encoding on
 stdout stands, we have at least to discuss about print-repr for
 unicode.

If you want to see this change really badly, you need to write a PEP.

 * on Windows for example the (good) mbcs_encode is anyway tolerant as
 it: unkown chars are mapped to '?' . I never had any objection to this.

Apparently, you haven't been dealing with character sets long enough.
I have seen *a lot* of objections to the way the CP_ACP encoding
deals with errors, e.g.

http://groups.google.com/group/comp.lang.python/msg/dea84298cb2673ef?dmode=sourcehl=en

When windows converts these file names in CP_ACP, then the
file names in a directory are not round-trippable. This is
a source of permanent pain.

 * I would also live perfectly with .encode(enc) to run 'replace' by
 default, and 'strict' on demand. None of my apps and scripts would
 break because of this, but win. A programmer is naturally very aware
 when he wants 'strict'. Can you name realistic cases where 'replace'
 behavior would be so critical that a program damages something?

File names. Replace an unencodable filename with a question mark,
and you get a pattern that matches multiple files. For example, do

get_deletable_files.py | xargs rm

and you remove much more files than you want to. Pretty catastrophic.

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


Re: another docs problem - imp

2006-01-13 Thread Kent Johnson
Steve Holden wrote:
 Clearly. So get your sleeves rolled up and provide a fix. Then you too 
 will get your name in the Python documentation contributors' list.

Is there such a list? I have contributed many doc patches and if such 
glory is mine I would like to know it!

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


Re: another docs problem - imp

2006-01-13 Thread Steve Holden
Kent Johnson wrote:
 Steve Holden wrote:
 
Clearly. So get your sleeves rolled up and provide a fix. Then you too 
will get your name in the Python documentation contributors' list.
 
 
 Is there such a list? I have contributed many doc patches and if such 
 glory is mine I would like to know it!
 
 Kent

There *is* one:

   http://docs.python.org/acks.html

but I don;t get to decide who goes on it.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: how do real python programmers work?

2006-01-13 Thread Roy Smith
Mike Meyer [EMAIL PROTECTED] wrote:
 we need a term for development environment built out of Unix tools

We already have one.  The term is emacs.
-- 
http://mail.python.org/mailman/listinfo/python-list


ldap .passwd method, need help

2006-01-13 Thread Sells, Fred
I've got the python-ldap version 2.0.11 with python 2.4 under Linux

I've got the ldap stuff working for groups, but now I'm trying to use it to
change a user password.  I get a return of 2 and no error messages but it
does not change ldap.

I've tried it with uid = 'joeblow' and with oldpw=whatever it was with the
same result.

Anyone know what I'm missing?

class LdapUser:
def __init__(self, uri=uri, binddn=BINDDN, password=):
self.ldap = ldap.initialize(uri)
self.ldap.simple_bind(binddn, password)

def chg_pw(self,uid,oldpw,newpw):
print self.ldap.passwd_s(uid,oldpw,newpw)


if __name__==__main__:
Ldap = LdapUser(password=secret)
Ldap.chg_pw(uid=joeblow,ou=abc,ou=def,dc=ghi,dc=org,, new.pass)


---
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


  1   2   3   >