Release of PyGreSQL 4.0 (update)

2009-01-03 Thread D'Arcy J.M. Cain
Update: The Windows binaries are now available on the web site.

We are please to announce the release of PyGreSQL 4.0.  his is a major
release and you should check it carefully before using in existing
applications.  There may be some incompatibilities.

PyGreSQL is a Python module that interfaces to a PostgreSQL
database. It embeds the PostgreSQL query library to allow easy use of
the powerful PostgreSQL features from a Python script.

For more information, please visit http://www.PyGreSQL.org/.

From the changelog:
- Dropped support for Python below 2.3 and PostgreSQL below 7.4.
- Improved performance of fetchall() for large result sets
  by speeding up the type casts (as suggested by Peter Schuller).
- Exposed exceptions as attributes of the connection object.
- Exposed connection as attribute of the cursor object.
- Cursors now support the iteration protocol.
- Added new method to get parameter settings.
- Added customizable row_factory as suggested by Simon Pamies.
- Separated between mandatory and additional type objects.
- Added keyword args to insert, update and delete methods.
- Added exception handling for direct copy.
- Release the GIL while making a connection
  (as suggested by Peter Schuller).
- If available, use decimal.Decimal for numeric types.
- Allow DB wrapper to be used with DB-API 2 connections
  (as suggested by Chris Hilton).
- Made private attributes of DB wrapper accessible.
- Dropped dependence on mx.DateTime module.
- Support for PQescapeStringConn() and PQescapeByteaConn();
  these are now also used by the internal _quote() functions.
- Added 'int8' to INTEGER types. New SMALLINT type.
- Added a way to find the number of rows affected by a query()
  with the classic pg module by returning it as a string.
  For single inserts, query() still returns the oid as an integer.
  The pgdb module already provides the rowcount cursor attribute
  for the same purpose.
- Improved getnotify() by calling PQconsumeInput() instead of
  submitting an empty command.
- Removed compatibility code for old OID munging style.
- The insert() and update() methods now use the returning clause
  if possible to get all changed values, and they also check in advance
  whether a subsequent select is possible, so that ongoing transactions
  won't break if there is no select privilege.
- Added protocol_version and server_version attributes.
- Revived the user attribute.
- The pg module now works correctly with composite primary keys;
  these are represented as frozensets.
- Removed the undocumented and actually unnecessary view parameter
  from the get() method.
- get() raises a nicer ProgrammingError instead of a KeyError
  if no primary key was found.
- delete() now also works based on the primary key if no oid available
  and returns whether the row existed or not.


-- 
D'Arcy J.M. Cain
PyGreSQL Development Group
http://www.PyGreSQL.org
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: Is there a better algorithm?

2009-01-03 Thread Hendrik van Rooyen
bearophile wrote:

Fuzzyman:

 for i in l:
  u = None
  if len(i) == 2:
   k, v = i
  else:
   k, u, v = i

That's the best solution I have seen in this thread so far (but I
suggest to improve indents and use better variable names). In
programming it's generally better to follow the KISS principle.

Strange that nobody has suggested:

for Tup in Lst:
  for item in Tup:
print item,
  print

Because if I recall correctly, all the OP was doing was printing the stuff.

Gets a bit hairier if you want to return the values though. - if you
replace the first print statement above with a yield and delete the
second, bare print, you lose knowledge of which tuple the item 
belongs to.

It is not trivial to do if you don't have a priori knowledge of
the maximum and minimum tuple length.

Seems to me it is one of those gems that is a PITA to do completely 
generally - basically because you don't know when you call it how
many items to unpack - so you have to return a count or something,
or just fall back on a two step approach - get the tuple from the list,
then do something with the items in the tuple.

- Hendrik


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


patch

2009-01-03 Thread Pavel Kosina
Týká se to Pythonu okrajově, přesto to dávám sem. Myslím, že by se mohlo 
hodit i ostatním, kdo chtějí zkoušet pod Windows nové věci z development 
verze:


Jak opatchovat (pythonýrský) soubor pod Windows? Co jsem udělal:

1/ stáhl jsem http://gnuwin32.sourceforge.net/packages/patch.htm
2/ nainstaloval pod amin, přidal cestu do ..bin .. do PATH
3/ stáhl http://bugs.python.org/file12561/conv.diff a uložil do Lib/idlelib
4/ cmd: patch  conf.diff hází chybu:

C:\prg\Python30\Lib\idlelibpatch  conv.diff
patching file IOBinding.py
Assertion failed: hunk, file ../patch-2.5.9-src/patch.c, line 354

This application has requested the Runtime to terminate it in an unusual 
way.

Please contact the application's support team for more information.

Patchuje někdo tady pod Windows? Díky


--
geon
Pavel Kosina

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


ACL in python

2009-01-03 Thread John Boloshevich
Hello,

does anybody know about an ACL implementation for python, which is not tied
to the filesystem? I would like to use ACL on different objects not on
files, so the POSIX file access solution is not the one I am looking for.

I would like to be able to define ACOs, AROs, but it would be even nicer, if
there would be AXO possibility as well.

I have tried to find already, but I wasn't really successful.

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


Re: Why not Ruby?

2009-01-03 Thread Marc 'BlackJack' Rintsch
On Fri, 02 Jan 2009 09:00:01 -0800, r wrote:

 On Jan 2, 6:45 am, Steven D'Aprano st...@remove-this-
 cybersource.com.au wrote:
 On Thu, 01 Jan 2009 17:38:02 -0800, r wrote:
  He was not cross posting.

 You don't actually know what cross-posting is, do you?

 You've just earned a plonking for the next month. Do try to have at
 least half a clue by February.
 
 Steven i got you NOW!
 Everybody go and look at this thread, there Mr. Makinzie butts in and
 posts an off-topic question, and Steven answers it, contributing to the
 off-topicalitly of the thread. And has yet to apologize for it, or admit
 his screwup, but will he preach to everyone else about making off topic
 post... Pot meet Kettle; Kettle Pot!
 
 http://groups.google.com/group/comp.lang.python/browse_thread/thread/
fc57c18c3cff5937?hl=enq=recycle+bin#97254d877903bbd

No you didn't got Steven, as unnecessary cross posting is something 
different than answering a question that should have been a new thread 
start.

Oh, and: *plonk* for your childish annoying behaviour…

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


Re: why cannot assign to function call

2009-01-03 Thread Marc 'BlackJack' Rintsch
On Fri, 02 Jan 2009 04:39:15 -0600, Derek Martin wrote:

 On Tue, Dec 30, 2008 at 02:21:29PM +, John O'Hagan wrote:
 What the Python community often overlooks, when this discussion again
 rears its ugly head (as it seems to every other hour or so), is that its
 assignment model is BIZARRE, as in it's conceptually different from
 virtually all other languages substantially taught in undergraduate
 computer science programs.

What's the difference between Python and Java or C# here!?  Or are they 
also BIZARRE!?

 And for that matter, it's pretty unintuitive generally.

Names and objects are quite natural IMHO.  There are many real world 
objects which we attach one or more names to, or refer to in sequences 
like please give me the third book on that shelve (``shelve[2]``).

 That is, in what I'll call normal computer languages, a variable name
 is thought of as the address of a bin where some data is stored, and the
 name is inexorably tied to that bin.

You just call that normal or intuitive because that's what you 
learned first.

 Python is very different from this.  Names are not addresses of bins;
 they are instead simply ephemeral labels which are given to bins, where
 the bin is a Python object which contains specific data at the time of
 assignment.  A second assignment of that name doesn't change what's in
 the original bin; it actually (probably) first creates a new bin, then
 removes the name from the original bin and assigns it to the new one. 
 Intuitively, it's a bit like saying your kitchen table is no longer a
 kitchen table, and now the thing where you wash your dishes is a kitchen
 table.  It doesn't really make a lot of sense (whether or not it's so
 for good reason), and it makes describing the assignment model
 necessarily convoluted, whereas the named bins model from the majority
 of other languages people are likely to have been exposed to is simple
 and sensible.

I think the bin model is more complex because you don't just have a 
name and an object but always that indirection of the bin.

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


Re: Ideas to optimize this getitem/eval call?

2009-01-03 Thread mario
On Jan 3, 7:16 am, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:

 I was about to make a comment about this being a security hole,

Strange that you say this, as you are also implying that *all* the
widely-used templating systems for python are security holes... Well,
you would be right to say that of course ;-) Infact, evoque is really
one of the few (or even the only one?) that was conceived from the
start to support restricted evaluation.

 but I see from here

 http://evoque.gizmojo.org/usage/restricted/

 that you are aware of at least some of the issues.

 I must say though, your choice of builtins to prohibit seems rather
 arbitrary. What is dangerous about (e.g.) id() and isinstance()?

Preventive, probably. I also feel that temlates should have any
business with info such as the memory addressed returnred by id(). For
isinstance, becuase it is somewhat related to __subclasses__ that is
known to be insecure.

Incidentally, I updated the page you point to clarify what is going
on. I also added a link to Brett Cannon's inspiration paper on the
topic of securing the python interpreter...

      except:
          # KeyError, NameError, AttributeError, SyntaxError,
          # ValueError, TypeError, IOError

 If you want to capture seven exceptions, then capture seven exceptions,
 not any exception.

Absolutely not. I want to catch ALL evaluation exceptions... it would
actually *be* a secuity hole to allow any exception to bubble. hey
will however be handled appropriately as per the application policy/
config/deployment.

 You should write:

     except (KeyError, NameError, ..., IOError):

 instead of a bare except clause. That will capture exceptions that
 represent bugs in your code as well as exceptions that should propbably
 be allowed to propagate, such as KeyboardInterupt and SystemExit.

Again, no. Template presentational logic has no business issuing
SystemExits or so. And, of course, there are no bugs in my code ;-)

          # Special case if a KeyError is coming from the self.codes[name]
          # lookup (traceback should consist of a single frame only):
          if sys.exc_info()[2].tb_next is None:
              if sys.exc_info()[0] is KeyError:
                  self.codes[expr] = compile(expr, 'string', 'eval')
                      return self[expr]

 That seems awfully complicated for no good reason.

Yes, you are probably right. I wanted to be precise in that if the
KeyError originates strictly from the codes lookup and not from the
actual eval of the expr itself -- in which case the expr should be
compiled and added to codes (yes, this is the first-time failure I
referred to in the first message).

I tested the performance of your 2 variations in context, and there
seems to be no noticeable performance gain (something like less than
1% gain). But note the two variations as you code them do not quite do
exactly the same test.

I have adjusted to use this code now:

def __getitem__(self, expr):
try:
return eval(self.codes[expr], self.globals, self.locals)
except:
# We want to catch **all** evaluation errors!
# KeyError, NameError, AttributeError, SyntaxError, V
# alueError, TypeError, IOError, ...
#
# Special case:
# if KeyError is coming from self.codes[expr] lookup,
# then we add the compiledentry and try again:
if not name in self.codes:
self.codes[expr] = compile(name, 'string', 'eval')
return self[expr]
# handle any other error...

This retains the correctness of the check, and has the same marginal
perf improvement (that is basically negligible, but at least it is not
slower) and has teh advantage that the code is clearer.

Thanks for the remarks!

mario

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


Re: ACL in python

2009-01-03 Thread Tino Wildenhain

John Boloshevich wrote:

Hello,

does anybody know about an ACL implementation for python, which is not 
tied to the filesystem? I would like to use ACL on different objects not 
on files, so the POSIX file access solution is not the one I am looking for.


You mean something like the restricted environment you find within zope
for all the TTW-stuff?

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ideas to optimize this getitem/eval call?

2009-01-03 Thread mario
correction: the code posted in previous message should have been:


def __getitem__(self, expr):
try:
return eval(self.codes[expr], self.globals, self.locals)
except:
# We want to catch **all** evaluation errors!
# KeyError, NameError, AttributeError, SyntaxError, V
# alueError, TypeError, IOError, ...
#
# Special case:
# if KeyError is coming from self.codes[expr] lookup,
# then we add the compiledentry and try again:
if not expr in self.codes:
self.codes[expr] = compile(expr, 'string', 'eval')
return self[expr]
# handle any other error...
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing vs thread performance

2009-01-03 Thread Nick Craig-Wood
mk mrk...@gmail.com wrote:
  After reading http://www.python.org/dev/peps/pep-0371/ I was under 
  impression that performance of multiprocessing package is similar to 
  that of thread / threading. However, to familiarize myself with both 
  packages I wrote my own test of spawning and returning 100,000 empty 
  threads or processes (while maintaining at most 100 processes / threads 
  active at any one time), respectively.
 
  The results I got are very different from the benchmark quoted in PEP 
  371. On twin Xeon machine the threaded version executed in 5.54 secs, 
  while multiprocessing version took over 222 secs to complete!
 
  Am I doing smth wrong in code below?

Yes!

The problem with your code is that you never start more than one
process at once in the multiprocessing example.  Just check ps when it
is running and you will see.

My conjecture is that this is due to the way fork() works under unix.
I think that when the parent forks it yields the CPU to the child.
Because you are giving the child effectively no work to do it returns
immediately, re-awakening the parent, thus serialising your jobs.

If you give the children some work to do you'll see a quite different
result.  I gave each child time.sleep(1) to do and cut down the total
number to 10,000.

$ ./test_multiprocessing.py
== Process 1000 working ==
== Process 2000 working ==
== Process 3000 working ==
== Process 4000 working ==
== Process 5000 working ==
== Process 6000 working ==
== Process 7000 working ==
== Process 8000 working ==
== Process 9000 working ==
== Process 1 working ==
=== Main thread waiting for all processes to finish ===
Total time: 101.382129192

$ ./test_threading.py
== Thread 1000 working ==
== Thread 2000 working ==
== Thread 3000 working ==
== Thread 4000 working ==
== Thread 5000 working ==
== Thread 6000 working ==
== Thread 7000 working ==
== Thread 8000 working ==
== Thread 9000 working ==
== Thread 1 working ==
Total time:  100.659118176

So almost identical results and as expected - we ran 10,000 sleep(1)s
in 100 seconds so we must have been running 100 simultaneously.

If you replace the time.sleep(1) with for _ in xrange(100):
pass you get this much more interesting answer on my dual core linux
laptop, showing nicely the effect of the contention on the python
global interpreter lock and how multiprocessing avoids it.

$ ./test_multiprocessing.py
== Process 1000 working ==
== Process 2000 working ==
== Process 3000 working ==
== Process 4000 working ==
== Process 5000 working ==
== Process 6000 working ==
== Process 7000 working ==
== Process 8000 working ==
== Process 9000 working ==
== Process 1 working ==
=== Main thread waiting for all processes to finish ===
Total time: 266.808327913

$ ./test_threading.py
== Thread 1000 working ==
== Thread 2000 working ==
== Thread 3000 working ==
== Thread 4000 working ==
== Thread 5000 working ==
== Thread 6000 working ==
== Thread 7000 working ==
== Thread 8000 working ==
== Thread 9000 working ==
== Thread 1 working ==
Total time:  834.81882

-- 
Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: greenlets and how they can be used

2009-01-03 Thread Mark Wooding
James Mills prolo...@shortcircuit.net.au wrote:

 The greenlet from http://codespeak.net/py/dist/greenlet.html
 is a rather interesting way of handling flow of control.

Ahh, yes.  It's actually a rather old idea, but too rarely used.

 What can greenlet's be used for ? What use-cases have you guys used
 them for (if any) ?

I've one project in which I use coroutines (either greenlets or some
coroutines I concocted out of Python's built-in threading) extensively.
The system consists of a server which speaks a text-based protocol
(written in C), a graphical monitor program, and a number of ancillary
services which are both clients of the server, and augment it by
providing additional commands.  The monitor and the services are all in
Python, and make extensive use of coroutines.

One reason for this is that some of the server's commands can take a
long time, so it's useful for the programs to be able to do other things
while they wait for replies.  Full-on threading would be possible, but
(a) in fact I make a /lot/ of coroutines, and (b) with coroutines I
don't have to think anywhere near as hard about synchronization.

You can browse about here, if you like:

  http://git.distorted.org.uk/gitweb/~mdw/tripe?a=tree;h=python

The main Python module is in py/; the services are in svc/, and the
graphical monitor is in mon/.

 Can they be used in place of threads with much the same effect - but
 more lightweight ?

More lightweight, and much easier to reason about.  They also confuse
other libraries less.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-03 Thread Bruno Desthuilliers

Derek Martin a écrit :

On Fri, Jan 02, 2009 at 09:05:51PM +0100, Bruno Desthuilliers wrote:

Python seems rather weird, and I think from the frequency
with which these discussions occur on this list, clearly it *IS*
difficult for a neophyte Python programmer to understand the
assignment model.
Took me about half an hour to grasp, not even being CS grad (nor  
whathever grad FWIW). By that time, I had a couple monthes working  
experience with VB, and had learned (but never seriously used) bits of  
C, C++, Java and Pascal.


It took me about a half a second to grasp the named bins concept --


Oh yes ? With all it's implications ? Fine, you're way smarter than I'm 
- or, as it seems, you were much more experimented and CS-litterate that 
I was by that time.


But that was not the point. What I meant is that a concept that takes 
less than an hour to grasp for a newbie self-taught programmer with no 
previous exposure to the concept should by no mean be a problem for a CS 
graduate.


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


Re: Noob question: Is all this typecasting normal?

2009-01-03 Thread Bruno Desthuilliers

sprad a écrit :

I've done a good bit of Perl, but I'm new to Python.

I find myself doing a lot of typecasting (or whatever this thing I'm
about to show you is called),


Actually, it's just plain object instanciation.


and I'm wondering if it's normal, or if
I'm missing an important idiom.

For example:

bet = raw_input(Enter your bet)
if int(bet) == 0:
# respond to a zero bet


raw_input() returns a string. If you want an int and the string is 
supposed to contain a legitimate string representation of an integer, 
then yes, passing the string to the int object constructor is the right 
thing to do. I'd just write it a bit diffently:


bet = int(raw_input(Enter your bet))
if bet == 0:
   # code here

or even better:

def read_int(prompt, err=Sorry, '%s' is not a valid integer):
   while True:
  answer = raw_input(prompt)
  try:
   return int(answer)
  except ValueError:
   print err % answer

bet = read_int(Enter your bet)
if bet == 0:
# code here


Or later, I'll have an integer, and I end up doing something like
this:

print You still have $ + str(money) +  remaining


May suggest learning about string formatting ?

   print You still have $%s remaining % money


But indeed, you obviously cannot add strings with numerics nor 
concatenate numerics with strings. This would make no sense.



All the time, I'm going int(this) and str(that). Am I supposed to?


Depends on the context.
--
http://mail.python.org/mailman/listinfo/python-list


Doubt on creating threads

2009-01-03 Thread koranthala
I was going through Python posts and this post caught my attention
http://groups.google.com/group/comp.lang.python/browse_thread/thread/f99326a4e5d394e/14cd708956bd1c1a#14cd708956bd1c1a

quote
 You have missed an important point. A well designed application does
 neither create so many threads nor processes. The creation of a
thread
 or forking of a process is an expensive operation. You should use a
pool
 of threads or processes.
/unquote

I am creating an application and it creates ~1-2 threads every second
and kill it within 10 seconds. After reading this I am worried. Is
creating a thread a very costly operation? I cannot use a pool of
threads because I am using an external application (twisted) to create
the threads (deferToThread).
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-03 Thread John O'Hagan
On Tue, 30th Dec 2008, Aaron Brady wrote:

Accepting that, I'll adopt the terms John proposed, 'change' vs.
'exchange', the former when the material configuration changes, the
latter when the communication axioms change.

b= [2, 3]
b= [3, 4]

'b' has exchanged.  (Somewhat ungrammatical.)

b= [2, 3]
b.append( 4 )

'b' has changed.

According to this, when you replace every floorboard on a porch, one
at a time, it's still the same porch-- it's changed, it's different,
and it's the same.  However, if you haul off the porch and put a new
one in its place, it's not.  ('porch[:]=' vs. 'porch='.)  You can't
just look at the initial and final configurations of matter to
determine so.  Therefore, 'id' is an informal function.

This analogy describes the ontological minefield I was referring to in a 
previous post in this thread (which has expired in my mail reader, so my 
apologies if the threading goes awry): In what sense is a porch (or list, or 
string) the same if all (or even some of) its parts have been exchanged? 

I think the answer is something to do with the abstraction, the container, 
the instance of the class. Would it be fair to say that perhaps there are no 
truly mutable objects, only immutable containers whose contents (also 
immutable objects themselves) may be exchanged? Or to pose the question 
another way, are objects only mutable insofar as they are composite?

As you argue above, the planks are not the porch; I would add that it's your 
_decision_ to build (or tear down) a porch which makes it _that_  particular
porch (or not). 

As you imply above (I think), you have to keep looking (or someone does, 
presumably the interpreter) to know whether an object is the same as or just 
equal to another (which starts to sound spookily like the role of the 
observer in phenomenology or quantum physics). Whether this means that id() 
is informal or not, I'll leave to others better informed than I.

Regards,

John


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


Re: select.select and socket.setblocking

2009-01-03 Thread Bryan Olson

Laszlo Nagy wrote:
[...]

I have read the socket programming howto (
http://docs.python.org/howto/sockets.html#sockets ) but it does not
explain how a blocking socket + select is different from a non blocking
socket + select. Is there any difference?


There is, but it may not effect you. There are cases where a socket can 
select() as readable, but not be readable by the time of a following 
recv() or accept() call. All such cases with which I'm familiar call for 
a non-blocking socket.


Where does this come up? Suppose that to take advantage of multi-core 
processors, our server runs as four processes, each with a single thread 
that responds to events via select(). Clients all connect to the same 
server port, so the socket listening on that port is shared by all four 
processes. A perfectly reasonable architecture (though with many more 
processes the simple implementation suffers the thundering herd problem).


Two of our processors may be waiting on select() when a new connections 
comes in. The select() call returns in both processes, showing the 
socket ready for read, so both call accept() to complete the connection. 
 The O.S. ensures that accept() [and recv()] are atomic, so one process 
gets the new connection; what happens in the other depends on whether we 
use a blocking or non-blocking socket, and clearly we want non-blocking.



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


Re: why cannot assign to function call

2009-01-03 Thread Grant Edwards
On 2009-01-03, Marc 'BlackJack' Rintsch bj_...@gmx.net wrote:
 On Fri, 02 Jan 2009 04:39:15 -0600, Derek Martin wrote:

 What the Python community often overlooks, when this discussion again
 rears its ugly head (as it seems to every other hour or so), is that its
 assignment model is BIZARRE, as in it's conceptually different from
 virtually all other languages substantially taught in undergraduate
 computer science programs.

 What's the difference between Python and Java or C# here!?

Or scheme, or lisp, or smalltalk, or 

 Or are they also BIZARRE!?

One presumes that Mr. Martin finds anything different from his
first computer language to be BIZARRE.  He should try out
Prolog or something genuinely different.

-- 
Grant

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


strange thing after call PyObject_CallMethod

2009-01-03 Thread Exe

Hello everybody!

I'm in trouble. This code shows that ob_refcnt increased by python
if on_recv method throws exception. This occurs only if base C-class  
subclassed

in python code.
==
my_old_refcnt = Py_REFCNT(self);
py_result = PyObject_CallMethod(self, on_recv, (y#), recvbuf, result);
my_new_refcnt = Py_REFCNT(self);

log_debug(refcnt before call %d, my_old_refcnt);
log_debug(after call: %d\n, my_new_refcnt);
==


Output:
==
tcpconn.c: refcnt before call 1
tcpconn.c: after call: 2
==

If PyObject_CallMethod returns success(any non-NULL value) anything okay.
Tested on Python 3.1a0 (py3k:68145M, Jan  2 2009, 20:51:28).

Why this happenning and who makes Py_INCREF(self)?


PS garbage collector knows about this so on exit
PyGC_Collect deletes instance.

--
//wbr
Kandalintsev Alexandre
--
http://mail.python.org/mailman/listinfo/python-list


Re: Doubt on creating threads

2009-01-03 Thread Jean-Paul Calderone

On Sat, 3 Jan 2009 08:39:52 -0800 (PST), koranth...@gmail.com wrote:

I was going through Python posts and this post caught my attention
http://groups.google.com/group/comp.lang.python/browse_thread/thread/f99326a4e5d394e/14cd708956bd1c1a#14cd708956bd1c1a

quote
You have missed an important point. A well designed application does
neither create so many threads nor processes. The creation of a
thread
or forking of a process is an expensive operation. You should use a
pool
of threads or processes.
/unquote

I am creating an application and it creates ~1-2 threads every second
and kill it within 10 seconds. After reading this I am worried. Is
creating a thread a very costly operation? I cannot use a pool of
threads because I am using an external application (twisted) to create
the threads (deferToThread).


Actually, deferToThread is implemented in terms of a thread pool.  So
you're only creating a small number of threads, and then they're being
re-used.

I somewhat disagree with the assertion that not using a threadpool means
that your application is well designed.  However, it's absolutely true
that using a threadpool lowers the runtime cost of using threads compared
to creating and destroying threads all the time.

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


Re: strange thing after call PyObject_CallMethod

2009-01-03 Thread Martin v. Löwis
 Why this happenning and who makes Py_INCREF(self)?

There are multiple possible explanations, but I think you
have ruled out most of them:

1. on_recv might be returning self. So py_result would be
   the same as self, and hence be an additional reference.
   However, you said that on_recv raised an exception, so
   py_result should be NULL (can you confirm?)

2. there might be a reference leak in the implementation of
   on_recv. However, you say that it is all fine at the
   end, so this is unlikely

3. The implementation of on_recv stores the object inside
   another objects. There are too many possibilities for that
   to enumerate; here are some examples:

   def on_recv(self, buf):
   global foo, bar
   foo = self  # creates global reference
   bar = self.on_send  # creates bound method
   self.foo = self # creates cyclic reference
   foobar.append(self) # adds self into container

If you are using gdb, I recommend to set a watchpoint on
changes to ob_refcnt:

(gdb) p ((PyObject*)self)-ob_refcnt
$1 = (Py_ssize_t *) 0xa0cb5a0
(gdb) watch *(Py_ssize_t *) 0xa0cb5a0
Hardware watchpoint 2: *(ssize_t *) 168605088
(gdb) c
Continuing.
Hardware watchpoint 2: *(ssize_t *) 168605088

Old value = 2
New value = 1
0xb7d5f406 in list_clear (a=0xa041c74) at Objects/listobject.c:550
550 Py_XDECREF(item[i]);

As you can see: this specific object was stored in a list, and
the list is now being cleared.

HTH,
Martin


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


Re: Noob question: Is all this typecasting normal?

2009-01-03 Thread Russ P.
On Jan 2, 10:50 pm, Ben Finney bignose+hates-s...@benfinney.id.au
wrote:
 s0s...@gmail.com writes:
  On Jan 2, 7:20 pm, Ben Finney bignose+hates-s...@benfinney.id.au
  wrote:
   They don't need to be creative; they merely need to conform with
   the naming scheme as laid out in the PEP.

  If it's something to be included in the standard library, I agree
  (just for consistency, not because using_underscores is better).

  But for user code, I prefer mixedCase.

 That seems superficially like an easy distinction. Indeed, PEP 8
 explicitly is meant to apply only to code intended for inclusion in
 the Python standard library.

 But consider:

 Python libraries generally don't get into the standard library until
 they've had a history of widespread public use as an external library.
 This helps ensure many of the harder-to-find wrinkles get discovered
 through wide exposure and ironed out before becoming standard.

 Code bases, especially library interfaces, that get a lot of use
 across wide communities are naturally going to have a whole lot of
 other people's code directly using those interfaces.

 Interfaces that are so widely used garner a high resistance to change,
 especially for something as non-functional as a naming convention.

 Choosing the naming convention for one's code is much easier to do
 when its usage base is smaller than when that base is larger.
 Therefore the easiest time to choose when to code in conformance to
 PEP 8 is right at the start.

 The best conclusion I can come to from this? Unless you explicitly
 *never* intend sharing your code with *anyone*, it's best to code all
 your Python code in accordance with PEP 8 anyway. You then don't have
 to make the decision about whether this is the time to follow PEP 8 or
 not; just do it by default, and you avoid the needless pain on those
 occasions, often unforeseeable at the start, where your code later
 ends up widely used.

 --
  \       “One of the most important things you learn from the internet |
   `\   is that there is no ‘them’ out there. It's just an awful lot of |
 _o__)                                            ‘us’.” —Douglas Adams |
 Ben Finney

Fair enough, but for code that is not intended for general public
usage (i.e., most code) so-called camelCase is every bit as good if
not better than using underscores to divide variable names. It saves a
few characters, and in my opinion it's significantly easier to read.
Identifiers divided by underscores always appear to me at first glance
to be multiple words, and I find that very annoying.

So unless you think the standard library will someday include code for
air traffic management, I'll stick with camelCase, and I'll thank you
for not making an issue of it.

As far as I am concerned, this is one of the most important bits of
advice in PEP 8:

A Foolish Consistency is the Hobgoblin of Little Minds
--
http://mail.python.org/mailman/listinfo/python-list


Re: Doubt on creating threads

2009-01-03 Thread Simon Forman
On Jan 3, 8:39 am, koranth...@gmail.com wrote:
 I was going through Python posts and this post caught my 
 attentionhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...

 quote
  You have missed an important point. A well designed application does
  neither create so many threads nor processes. The creation of a
 thread
  or forking of a process is an expensive operation. You should use a
 pool
  of threads or processes.
 /unquote

 I am creating an application and it creates ~1-2 threads every second
 and kill it within 10 seconds. After reading this I am worried. Is
 creating a thread a very costly operation? I cannot use a pool of
 threads because I am using an external application (twisted) to create
 the threads (deferToThread).

Generally you should only worry about this sort of thing if A) you
actually notice a performance problem and B) testing indicates that
it's thread creation which is causing it.

Otherwise you could spend a lot of time working on something that
doesn't actually affect your app's performance.

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


Re: Returning a string

2009-01-03 Thread Diez B. Roggisch

Kless schrieb:

How is possible that I can print a variable, but when I use *return
var* it returns an empty string

http://paste.pocoo.org/show/97588/


I don't see anything that indicates that the returned object is the 
empty string. Simply because there is no code testing for that. And of 
course you don't show any debugging output, which doesn't help either.


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


Re: Returning a string

2009-01-03 Thread Kless
On 3 ene, 19:12, Diez B. Roggisch de...@nospam.web.de wrote:
 Kless schrieb:

  How is possible that I can print a variable, but when I use *return
  var* it returns an empty string

 http://paste.pocoo.org/show/97588/

 I don't see anything that indicates that the returned object is the
 empty string. Simply because there is no code testing for that. And of
 course you don't show any debugging output, which doesn't help either.

 Diez

Afghanistan
AF
Out[19]: u'AF'
AFG
Out[19]: u'AFG'
004
Out[19]: u'004'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a string

2009-01-03 Thread Simon Forman
On Jan 3, 11:20 am, Kless jonas@googlemail.com wrote:
 On 3 ene, 19:12, Diez B. Roggisch de...@nospam.web.de wrote:

  Kless schrieb:

   How is possible that I can print a variable, but when I use *return
   var* it returns an empty string

  http://paste.pocoo.org/show/97588/

  I don't see anything that indicates that the returned object is the
  empty string. Simply because there is no code testing for that. And of
  course you don't show any debugging output, which doesn't help either.

  Diez

 Afghanistan
 AF
 Out[19]: u'AF'
 AFG
 Out[19]: u'AFG'
 004
 Out[19]: u'004'

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


Re: Returning a string

2009-01-03 Thread Kless
On 3 ene, 19:40, Simon Forman sajmik...@gmail.com wrote:
 On Jan 3, 11:20 am, Kless jonas@googlemail.com wrote:

  Afghanistan
  AF
  Out[19]: u'AF'
  AFG
  Out[19]: u'AFG'
  004
  Out[19]: u'004'

 What?

That's the output got from ipython. As you can see, it prints
'Afghanistan' but it can not returns it. In change, the another
strings are returned.

Could it be because it isn't returning the value from the
recursivecall?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a string

2009-01-03 Thread Diez B. Roggisch

Kless schrieb:

On 3 ene, 19:12, Diez B. Roggisch de...@nospam.web.de wrote:

Kless schrieb:


How is possible that I can print a variable, but when I use *return
var* it returns an empty string
http://paste.pocoo.org/show/97588/

I don't see anything that indicates that the returned object is the
empty string. Simply because there is no code testing for that. And of
course you don't show any debugging output, which doesn't help either.

Diez


Afghanistan
AF
Out[19]: u'AF'
AFG
Out[19]: u'AFG'
004
Out[19]: u'004'


What is that? IPython? And I don't see no empty string here. *What* I 
see is the way python's interactive prompt puts out strings, like this:


 unicode(foo)
u'foo'

Do you mean by any chance that you don't understand why print prints 
foo, but the prompt shows ufoo? That is because the prompt invokes


repr(o)

to print out an object:

 print repr(unicode(foo))
u'foo'

Which means that the output includes quotes and the u-prefix in case 
of an unicode object to help the user to see what the current object 
looks like.


Diez

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


Re: Returning a string

2009-01-03 Thread Diez B. Roggisch

Kless schrieb:

On 3 ene, 19:40, Simon Forman sajmik...@gmail.com wrote:

On Jan 3, 11:20 am, Kless jonas@googlemail.com wrote:


Afghanistan
AF
Out[19]: u'AF'
AFG
Out[19]: u'AFG'
004
Out[19]: u'004'

What?


That's the output got from ipython. As you can see, it prints
'Afghanistan' but it can not returns it. In change, the another
strings are returned.

Could it be because it isn't returning the value from the
recursivecall?


Yep, I guess that's the problem. You need to do

if cell_tag:
   return clean_tags(cell_tag)


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


Re: Returning a string

2009-01-03 Thread Marc 'BlackJack' Rintsch
On Sat, 03 Jan 2009 11:46:10 -0800, Kless wrote:

 On 3 ene, 19:40, Simon Forman sajmik...@gmail.com wrote:
 On Jan 3, 11:20 am, Kless jonas@googlemail.com wrote:

  Afghanistan
  AF
  Out[19]: u'AF'
  AFG
  Out[19]: u'AFG'
  004
  Out[19]: u'004'

 What?
 
 That's the output got from ipython. As you can see, it prints
 'Afghanistan' but it can not returns it. In change, the another strings
 are returned.

Maybe you should show the *input* too…

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


Re: Returning a string

2009-01-03 Thread Kless
On 3 ene, 19:51, Diez B. Roggisch de...@nospam.web.de wrote:
 Kless schrieb:



  On 3 ene, 19:40, Simon Forman sajmik...@gmail.com wrote:
  On Jan 3, 11:20 am, Kless jonas@googlemail.com wrote:

  Afghanistan
  AF
  Out[19]: u'AF'
  AFG
  Out[19]: u'AFG'
  004
  Out[19]: u'004'
  What?

  That's the output got from ipython. As you can see, it prints
  'Afghanistan' but it can not returns it. In change, the another
  strings are returned.

  Could it be because it isn't returning the value from the
  recursivecall?

 Yep, I guess that's the problem. You need to do

 if cell_tag:
     return clean_tags(cell_tag)

 Diez

Thank you very much. It works now.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse order of bit in repeating seqence of byte string

2009-01-03 Thread imageguy
On Jan 2, 7:33 pm, John Machin sjmac...@lexicon.net wrote:

 For some very strange definition of works. You say you have 'bgr'
 and want to convert it to 'rbg'. The following code converts 'bgr' to
 'rgb', which is somewhat more plausible, but not what you said you
 wanted.

Well that's embarrassing ... you are correct.  I need to convert from
'bgr' to 'rgb'

Thanks to all others for suggestions

FWIW, I realized the the C.types string buffer is/was mutable so
settled on this;

for start in xrange(0, ctypes.sizeof(buffer), 3):
if buffer[start] != buffer[start+2]:
 #only need to swap the bits if they are different.  ie if
both are white or black, no change is required.
 blue, red = buffer[start], buffer[start+2]
 buffer[start], buffer[start+2] = red, blue

This was about 30-40% faster that converting to list, processing and
then converting back again.

Will try the array module too
... but I think I need to find a new graphic package rather that makes
working with the bits easier.

g.

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


Re: Noob question: Is all this typecasting normal?

2009-01-03 Thread alex goretoy
for each his own.

Any more word on userio?

On Sat, Jan 3, 2009 at 6:14 PM, Russ P. russ.paie...@gmail.com wrote:

 On Jan 2, 10:50 pm, Ben Finney 
 bignose+hates-s...@benfinney.id.aubignose%2bhates-s...@benfinney.id.au
 
 wrote:
  s0s...@gmail.com writes:
   On Jan 2, 7:20 pm, Ben Finney 
   bignose+hates-s...@benfinney.id.aubignose%2bhates-s...@benfinney.id.au
 
   wrote:
They don't need to be creative; they merely need to conform with
the naming scheme as laid out in the PEP.
 
   If it's something to be included in the standard library, I agree
   (just for consistency, not because using_underscores is better).
 
   But for user code, I prefer mixedCase.
 
  That seems superficially like an easy distinction. Indeed, PEP 8
  explicitly is meant to apply only to code intended for inclusion in
  the Python standard library.
 
  But consider:
 
  Python libraries generally don't get into the standard library until
  they've had a history of widespread public use as an external library.
  This helps ensure many of the harder-to-find wrinkles get discovered
  through wide exposure and ironed out before becoming standard.
 
  Code bases, especially library interfaces, that get a lot of use
  across wide communities are naturally going to have a whole lot of
  other people's code directly using those interfaces.
 
  Interfaces that are so widely used garner a high resistance to change,
  especially for something as non-functional as a naming convention.
 
  Choosing the naming convention for one's code is much easier to do
  when its usage base is smaller than when that base is larger.
  Therefore the easiest time to choose when to code in conformance to
  PEP 8 is right at the start.
 
  The best conclusion I can come to from this? Unless you explicitly
  *never* intend sharing your code with *anyone*, it's best to code all
  your Python code in accordance with PEP 8 anyway. You then don't have
  to make the decision about whether this is the time to follow PEP 8 or
  not; just do it by default, and you avoid the needless pain on those
  occasions, often unforeseeable at the start, where your code later
  ends up widely used.
 
  --
   \   One of the most important things you learn from the internet |
`\   is that there is no 'them' out there. It's just an awful lot of |
  _o__)'us'. —Douglas Adams |
  Ben Finney

 Fair enough, but for code that is not intended for general public
 usage (i.e., most code) so-called camelCase is every bit as good if
 not better than using underscores to divide variable names. It saves a
 few characters, and in my opinion it's significantly easier to read.
 Identifiers divided by underscores always appear to me at first glance
 to be multiple words, and I find that very annoying.

 So unless you think the standard library will someday include code for
 air traffic management, I'll stick with camelCase, and I'll thank you
 for not making an issue of it.

 As far as I am concerned, this is one of the most important bits of
 advice in PEP 8:

 A Foolish Consistency is the Hobgoblin of Little Minds
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


ResponseNotReady exception

2009-01-03 Thread asit
import httplib

class Server:
#server class
def __init__(self, host):
self.host = host
def fetch(self, path):
http = httplib.HTTPConnection(self.host)
http.putrequest(GET, path)
r = http.getresponse()
print str(r.status) +   :   + r.reason


server = Server(www.python.org)
fp=open(phpvuln.txt)
x=fp.readlines();
for y in x:
 server.fetch(/ + y);

In the above code the phpvuln.txt file contains a list of directories.

Why the above code throws ResponseNotReady exception ???

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


Re: select.select and socket.setblocking

2009-01-03 Thread Saju Pillai

Bryan Olson fakeaddr...@nowhere.org wrote:


Where does this come up? Suppose that to take advantage of multi-core 
processors, our server runs as four processes, each with a single thread 
that responds to events via select(). Clients all connect to the same 
server port, so the socket listening on that port is shared by all four 
processes. A perfectly reasonable architecture (though with many more 
processes the simple implementation suffers the thundering herd problem).


Which is why it is common for real world servers to serialize the
select()/accept() code - usually via a file lock or a semaphore.
-srp 
-- 
http://saju.net.in


Two of our processors may be waiting on select() when a new connections 
comes in. The select() call returns in both processes, showing the 
socket ready for read, so both call accept() to complete the connection. 
  The O.S. ensures that accept() [and recv()] are atomic, so one process 
gets the new connection; what happens in the other depends on whether we 
use a blocking or non-blocking socket, and clearly we want non-blocking.


-- 
--Bryan





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


Re: Noob question: Is all this typecasting normal?

2009-01-03 Thread vk
 Any more word on userio?

None yet, I'm afraid. Should've started a different thread for it -
but it's stuck here (in obscurity) forever xd.
--
http://mail.python.org/mailman/listinfo/python-list


Re: strange thing after call PyObject_CallMethod

2009-01-03 Thread Bug Hunter

Thank you for so amazing debugging tutorial :).
I owe you a beer.

I found source of problem: then unhandled in python code
exception occurs frame_dealloc() (Objects/frameobject.c:422)
not called. Even if I call PyErr_Print().

But! If I call PyErr_Clear() then all okay!
Docs says that both this functions clears error indicator...
I hit a bug or my brains overheated?

Some gdb output if you are intrested:
Without exception: http://dpaste.com/104973/
With exception: http://dpaste.com/104975/
--
http://mail.python.org/mailman/listinfo/python-list


Re: ResponseNotReady exception

2009-01-03 Thread Chris Rebert
On Sat, Jan 3, 2009 at 12:38 PM, asit lipu...@gmail.com wrote:
 import httplib

 class Server:
#server class
def __init__(self, host):
self.host = host
def fetch(self, path):
http = httplib.HTTPConnection(self.host)
http.putrequest(GET, path)

According to the docs, if you use .putrequest(), you have to also then
call .putheader() [as many times as necessary], .endheaders(), and
.send(), in that order. I'd advise just changing .putrequest() to
.request() instead.

And you should also read the fine docs yourself:
http://docs.python.org/library/httplib.html

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Port of python stdlib to other languages.

2009-01-03 Thread vk
Have there been ports of the Python standard library to other
languages?

I would imagine using pickle, urllib, and sys in C (with pythonic
naming conventions) would be easier than using other libraries to do
the same thing.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Port of python stdlib to other languages.

2009-01-03 Thread Diez B. Roggisch

vk schrieb:

Have there been ports of the Python standard library to other
languages?

I would imagine using pickle, urllib, and sys in C (with pythonic
naming conventions) would be easier than using other libraries to do
the same thing.


AFAIK not. You could try elmer (found on SF) to expose these as C-DLL. 
However, I doubt this will be widely adopted - to much hassle, 
especially for OO-style interfaces. Those aren't properly exposable.



What do you need C for anyway? Or, to put it the other way round - why 
not expose whatever you need in C as python extension, and write your 
app in Python?


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


win32gui

2009-01-03 Thread Gandalf
Hi,
I'm trying to capture the text word under the user cursor,
so I was searching the win32 lib for functions I can use.
i used this to fined the controller under the cursor
win32gui.WindowFromPoint(win32gui.GetCursorPos())
 to get the controller, but then when I try to read the text with this
GetWindowText function it most of the time doesn't work, all the
getline methon like the following didn't worked in most of the time
too
win32gui.SendMessage(hwnd, win32con.EM_GETLINE, line, linetext)

I found this GetCharFromPosition in a VB forum  which sound promising
but unfortunately  it's not part of the win32gui for python

so now i'm looking for a reliable way to rich text from a controller
or position if you know a function who may do it or a better way
please tell me/
thank you and have a nice day
--
http://mail.python.org/mailman/listinfo/python-list


Re: ResponseNotReady exception

2009-01-03 Thread asit
On Jan 4, 1:59 am, Chris Rebert c...@rebertia.com wrote:
 On Sat, Jan 3, 2009 at 12:38 PM, asit lipu...@gmail.com wrote:
  import httplib

  class Server:
     #server class
     def __init__(self, host):
         self.host = host
     def fetch(self, path):
         http = httplib.HTTPConnection(self.host)
         http.putrequest(GET, path)

 According to the docs, if you use .putrequest(), you have to also then
 call .putheader() [as many times as necessary], .endheaders(), and
 .send(), in that order. I'd advise just changing .putrequest() to
 .request() instead.

 And you should also read the fine docs 
 yourself:http://docs.python.org/library/httplib.html

 Cheers,
 Chris

 --
 Follow the path of the Iguana...http://rebertia.com

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


compiling python2.5 on linux under wine

2009-01-03 Thread Luke Kenneth Casson Leighton
hey, has anyone investigated compiling python2.5 using winegcc, under wine?

i'm presently working my way through it, just for kicks, and was
wondering if anyone would like to pitch in or stare at the mess under
a microscope.
it's not as crazed as it sounds.  cross-compiling python2.5 for win32
with mingw32 is an absolute miserable bitch of a job that goes
horribly wrong when you actually try to use the minimalist compiler to
do any real work.
so i figured that it would be easier to get python compiled using
wine.  i _have_ got some success - a python script and a python.exe.so
(which is winegcc's friendly way of telling you you have something
that stands a chance of working) as well as a libpython25.dll.so.
what i _don't_ yet have is an _md5.dll (or should it be _md5.lib?)
i.e. the standard modules are a bit... iffy.  the _winreg.o is
compiled; the _md5.o is compiled; the winreg.lib is not.  whoops.
plus, it's necessary to enable nt_dl.c which is in PC/ _not_ in
Modules/.

one of the key issues that's a bit of a bitch is that python is
compiled up for win32 with a hard-coded pyconfig.h which someone went
to a _lot_ of trouble to create by hand instead of using autoconf.  oh
- and it uses visualstudio so there's not even a Makefile.  ignoring
that for the time-being was what allowed me to get as far as actually
having a python interpreter (with no c-based modules).

so there's a whole _stack_ of stuff that needs dragging kicking and
screaming into the 21st century.


there _is_ a reason why i want to do this.  actually, there's two.

firstly, i sure as shit do _not_ want to buy, download, install _or_
run visual studio.  i flat-out refuse to run an MS os and visual
studio runs like a dog under wine.

secondly, i want a python25.lib which i can use to cross-compile
modules for poor windows users _despite_ sticking to my principles and
keeping my integrity as a free software developer.

thirdly i'd like to cross-compile pywebkitgtk for win32

fourthly i'd like to compile and link applications to the extremely
successful and well wicked MSHTML.DLL... in the _wine_ project :)  not
the one in windows (!)  i want to experiment with DOM model
manipulation - from python - similar to the OLPC HulaHop project -
_but_ i want to compile or cross-compile everything from linux, not
windows (see 1 above)

fifthly i'd like to see COM (DCOM) working and pywin32 compiled and
useable under wine, even if it means having to get a license to use
dcom98 and oleauth.lib and oleauth.h etc. and all the developer files
needed to link DCOM applications under windows.  actually what i'd
_really_ like to see is FreeDCE's DCOM work actually damn well
finished, it's only been eight years since wez committed the first
versions of the IDL and header files, and it's only been over fifteen
years since microsoft began its world domination using COM and DCOM.

... but that's another story :)

so that's  ... five reasons not two.  if anyone would like to
collaborate on a crazed project with someone who can't count, i'm
happy to make available what i've got up to so far, on github.org.

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


Re: select.select and socket.setblocking

2009-01-03 Thread Roy Smith
Bryan Olson fakeaddr...@nowhere.org wrote:

 There are cases where a socket can select() as readable, but not be 
 readable by the time of a following recv() or accept() call. All such 
 cases with which I'm familiar call for a non-blocking socket.

I used to believe that if select() said data was ready for reading, a 
subsequent read/recv/recvfrom() call could not block.  It could return an 
error, but it could not block.  I was confident of this until just a few 
months ago when reality blew up in my face.

The specific incident involved a bug in the linux kernel.  If you received 
an UDP packet with a checksum error, the select() would return when the 
packet arrived, *before* the checksum was checked.  By the time you did the 
recv(), the packet had been discarded and the recv() would block.

This led me on a big research quest (including some close readings of 
Stevens, which appeared to say that this couldn't happen).  The more I 
read, the more I (re) discovered just how vague and poorly written the 
Berkeley Socket API docs are :-)

The bottom line is that Bryan is correct -- regardless of what the various 
man pages and textbooks say, in the real world, it is possible for a read() 
to block after select() says the descriptor is ready.  The right way to 
think about select() is to treat it as a heuristic which can make a polling 
loop more efficient, but should never be relied upon to predict the future.

Neither the negative nor positive behavior is guaranteed.  There's no 
guaranteed response time; just because select() hasn't returned yet doesn't 
mean a descriptor couldn't be read without blocking in another thread right 
now.  And, just because it has returned, that doesn't mean by the time you 
get around to reading, there will still be anything there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: math module for Decimals

2009-01-03 Thread Mark Dickinson
On Dec 31 2008, 11:02 pm, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:
 On Sun, 28 Dec 2008 06:38:32 -0800, Mark Dickinson wrote:
  On Dec 28, 7:28 am, Steven D'Aprano st...@remove-this-
  cybersource.com.au wrote:
  Ah crap, I forgot that from_float() has been left out of the decimal
  API. That's very annoying.

  Agreed.  It's maybe even annoying enough that a feature request at
  bugs.python.org might be honoured.  (Hint, hint!)

 I can take a hint :)

 http://bugs.python.org/issue4796#

Decimal.from_float() implemented by Raymond Hettinger for Python 2.7
and Python 3.1, within 72 hours of Steven submitting the feature
request.  If only all issues could be resolved this quickly. :-)

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


Re: math module for Decimals

2009-01-03 Thread Mark Dickinson
On Jan 3, 9:27 pm, Mark Dickinson dicki...@gmail.com wrote:
 Decimal.from_float() implemented by Raymond Hettinger for Python 2.7
 and Python 3.1, within 72 hours of Steven submitting the feature
 request.  If only all issues could be resolved this quickly. :-)

Rats.  I left out the crucial line of that post, namely:

Thank you, Steven!

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


Re: Reverse order of bit in repeating seqence of byte string

2009-01-03 Thread John Machin
On Jan 4, 7:10 am, imageguy imageguy1...@gmail.com wrote:
 On Jan 2, 7:33 pm, John Machin sjmac...@lexicon.net wrote:

  For some very strange definition of works. You say you have 'bgr'
  and want to convert it to 'rbg'. The following code converts 'bgr' to
  'rgb', which is somewhat more plausible, but not what you said you
  wanted.

 Well that's embarrassing ... you are correct.  I need to convert from
 'bgr' to 'rgb'

 Thanks to all others for suggestions

 FWIW, I realized the the C.types string buffer is/was mutable so
 settled on this;

 for start in xrange(0, ctypes.sizeof(buffer), 3):
     if buffer[start] != buffer[start+2]:
          #only need to swap the bits if they are different.  ie if
 both are white or black, no change is required.
          blue, red = buffer[start], buffer[start+2]
          buffer[start], buffer[start+2] = red, blue

You are likely find that using
buffer[start], buffer[start+2] = buffer[start+2], buffer[start]
is faster.

Cheers,
John

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


deleting a method

2009-01-03 Thread Filip Gruszczyński
I am trying to delete a method from a class. It's easy to delete other
attributes, but when I try:

 class A:
... def foo():
... pass
...
 a = A()
 del a.foo

I get

Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: A instance has no attribute 'foo'

Why is it so and how may still delete it?

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: deleting a method

2009-01-03 Thread MRAB

Filip Gruszczyński wrote:

I am trying to delete a method from a class. It's easy to delete other
attributes, but when I try:


class A:

... def foo():
... pass
...

a = A()
del a.foo


I get

Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: A instance has no attribute 'foo'

Why is it so and how may still delete it?

'a' is an instance of class A. You're trying to delete 'foo' from the 
instance.

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


Re: deleting a method

2009-01-03 Thread Ben Finney
MRAB goo...@mrabarnett.plus.com writes:

 Filip Gruszczyński wrote:
  Traceback (most recent call last):
File stdin, line 1, in module
  AttributeError: A instance has no attribute 'foo'
 
  Why is it so and how may still delete it?
 
 'a' is an instance of class A. You're trying to delete 'foo' from
 the instance.

To answer the second question: since ‘foo’ is an attribute of the
class ‘A’, you can delete the attribute from the class.

 class A(object):
... def foo(self):
... pass
... 
 a = A()
 'foo' in dir(a)
True
 del A.foo
 'foo' in dir(a)
False

-- 
 \   “If you don't know what your program is supposed to do, you'd |
  `\ better not start writing it.” —Edsger W. Dijkstra |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing if an index is in a slice

2009-01-03 Thread Bryan Olson

ajaksu wrote:

On Jan 1, 4:12 pm, mma...@gmx.net wrote:

I would like to check if an index is in a slice or not without
iterating over the slice.

Something like:


isinslice(36, slice(None, 34, -1))

True


I think it'd be feasible for slices that can be mapped to ranges[1],
but slices are more flexible than that.


If we add a parameter for the length of the list to which the slice is 
applied, then inslice() is well-defined.


I thought it would easy to write, but that was hours ago when I knew 
less about Python slice indexing than I do now. And I thought I new a 
bunch from writing a virtual slice class.


I'm leaning towards mmanns' idea that this should be built in. Handling 
all the cases is remarkably tricky. Here's a verbose version, with a 
little test:



def inslice(i, slc, length):
 Would index i be part of slice slc of a list of len length?


step = slc.step or 1

if step  0:

if slc.start is None:
start = 0
elif slc.start = 0:
start = slc.start
else:
start = max(0, length + slc.start)

if slc.stop is None:
stop = length
elif slc.stop = 0:
stop = min(length, slc.stop)
else:
stop = length + slc.stop

return start = i  stop and (i - start) % step == 0

else:

if slc.start is None:
start = length - 1
elif slc.start = 0:
start = min(length - 1, slc.start)
else:
start = length + slc.start

if slc.stop is None:
stop = -1
elif slc.stop = 0:
stop = slc.stop
else:
stop = max(-1, length + slc.stop)

return start = i  stop and (start - i) % (-step) == 0



# test
for start in [None, 0, 1, -1, -3, 4]:
for stop in [None, 0, 1, -1, 3, -5]:
for step in [None, 1, -1, 2, -3]:
for n in [0, 1, 2, 3, 5, 11, 16]:
slc = slice(start, stop, step)
s1 = [i for i in range(-3, n + 5) if inslice(i, slc, n)]
s2 = sorted(range(n)[slc])
assert s1 == s2



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


Re: why cannot assign to function call

2009-01-03 Thread Aaron Brady
On Jan 3, 11:25 am, John O'Hagan resea...@johnohagan.com wrote:
 On Tue, 30th Dec 2008, Aaron Brady wrote:
 Accepting that, I'll adopt the terms John proposed, 'change' vs.
 'exchange', the former when the material configuration changes, the
 latter when the communication axioms change.

 b= [2, 3]
 b= [3, 4]

 'b' has exchanged.  (Somewhat ungrammatical.)

 b= [2, 3]
 b.append( 4 )

 'b' has changed.

 According to this, when you replace every floorboard on a porch, one
 at a time, it's still the same porch-- it's changed, it's different,
 and it's the same.  However, if you haul off the porch and put a new
 one in its place, it's not.  ('porch[:]=' vs. 'porch='.)  You can't
 just look at the initial and final configurations of matter to
 determine so.  Therefore, 'id' is an informal function.

 This analogy describes the ontological minefield I was referring to in a
 previous post in this thread (which has expired in my mail reader, so my
 apologies if the threading goes awry): In what sense is a porch (or list, or
 string) the same if all (or even some of) its parts have been exchanged?

 I think the answer is something to do with the abstraction, the container,
 the instance of the class. Would it be fair to say that perhaps there are no
 truly mutable objects, only immutable containers whose contents (also
 immutable objects themselves) may be exchanged? Or to pose the question
 another way, are objects only mutable insofar as they are composite?

 As you argue above, the planks are not the porch; I would add that it's your
 _decision_ to build (or tear down) a porch which makes it _that_  particular
 porch (or not).

 As you imply above (I think), you have to keep looking (or someone does,
 presumably the interpreter) to know whether an object is the same as or just
 equal to another (which starts to sound spookily like the role of the
 observer in phenomenology or quantum physics). Whether this means that id()
 is informal or not, I'll leave to others better informed than I.

 Regards,

 John

I think the key ingredient is that there's no such thing as side
effect in math.

In example,

a= [0, 1, 2]
a[:]= [3, 4, 5]

There aren't many natural language senses in which 'a' is the same
object as before.  If I have a leg transplant, I'm the same person,
but if you replace the entire contents of me, I'm not.  But 'a' is.

The porch is defined by its location, but not exclusively.  Natural
language identity is a cluster concept, without strict necessary and
sufficient conditions.  Nothing really presses our boundaries of it
that much; there aren't many practical questions that lay out the
facts, then ask, 'But is it the same?'  You can replace the porch
board-at-a-time, and it is; and you can haul it somewhere and it is.
But rearrange the same boards, and it's not.  Continuity of form is
probably the prevalent feature, which as you state, does break down in
the case of composite (piece-wise) transformations.

You might get farther comparing container objects to spots on a
bulletin board.  The only thing that goes 'in' a container is a
denoting phrase to another object (and by the way, not a description);
the other also has its own spot independently on the board.

It's not clear IMO that the question is so much a minefield-- a
question that it's really easy to get throw (fall) off course
pursuing, as it is that there's no such course.  In short, there is no
such thing as composite identity, only matter; or in Python, only
spots on the bulletin board.

 Or to pose the question
 another way, are objects only mutable insofar as they are composite?

No; tuples are composite.  If I flip one bit in a byte somewhere, is
it the same byte?
--
http://mail.python.org/mailman/listinfo/python-list


Re: socket send help

2009-01-03 Thread Bryan Olson

Gabriel Genellina wrote:

greyw...@gmail.com escribió:

[...]

A simple server:

from socket import *
myHost = ''


Try with myHost = '127.0.0.1' instead - a firewall might be blocking 
your server.


Just a nit: I'd say the reason to use '127.0.0.1' instead of the empty 
string is that a firewall might *not* be blocking your server.


The Python sockets module interprets the empty string as INADDR_ANY, 
which means to bind to all available adapters including the loopback, 
A.K.A localhost, A.K.A '127.0.0.1'.



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


Re: Doubt on creating threads

2009-01-03 Thread Bryan Olson

koranth...@gmail.com wrote:

I am creating an application and it creates ~1-2 threads every second
and kill it within 10 seconds. After reading this I am worried. Is
creating a thread a very costly operation? 


Compared to a procedure call it's expensive, but a couple threads per 
second is insignificant. My out-dated Pentium 4 desktop can create and 
destroy a few thousand threads per second under WinXP; more under recent 
Linux.



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


Re: Noob question: Is all this typecasting normal?

2009-01-03 Thread Steven D'Aprano
On Sat, 03 Jan 2009 20:35:25 +, alex goretoy wrote:

 for each his own.

Please don't top-post.

Please don't quote the ENTIRE body of text (PLUS doubling it by including 
a completely useless HTML version) just to add a trivial comment. Trim 
the text you are replying to.


 Any more word on userio?

I doubt many people care about it. Why don't you write it, put it up on 
the Cheeseshop, and see if anyone uses it? Just because you think it is 
useful doesn't mean others do, but if they do, then great.


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


Re: math module for Decimals

2009-01-03 Thread Steven D'Aprano
On Sat, 03 Jan 2009 13:34:11 -0800, Mark Dickinson wrote:

 On Jan 3, 9:27 pm, Mark Dickinson dicki...@gmail.com wrote:
 Decimal.from_float() implemented by Raymond Hettinger for Python 2.7
 and Python 3.1, within 72 hours of Steven submitting the feature
 request.  If only all issues could be resolved this quickly. :-)
 
 Rats.  I left out the crucial line of that post, namely:
 
 Thank you, Steven!

And many thanks to both you and Raymond, firstly for doing the actual 
work, and secondly for your patience with my questions on the bug tracker.


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


Re: Noob question: Is all this typecasting normal?

2009-01-03 Thread Steven D'Aprano
On Sat, 03 Jan 2009 16:19:58 +0100, Bruno Desthuilliers wrote:

 But indeed, you obviously cannot add strings with numerics nor
 concatenate numerics with strings. This would make no sense.

The OP comes from a Perl background, which AFAIK allows you to concat 
numbers to strings and add strings to numbers. That's probably the (mis)
feature he was hoping Python had.



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


Re: Why not Ruby?

2009-01-03 Thread Jack.Chu
On Jan 1, 3:55 am, Roger rdcol...@gmail.com wrote:
 On Dec 31, 12:55 pm, Xah Lee xah...@gmail.com wrote:

  Just spent 3 hours looking into Ruby today. Here's my short impression
  for those interested.

 Who are you?

 In case no one tells you, you are a cocky, egotistical windbag with
 opinions that border constructive but never gets there.  Why would
 anyone care what you think?  Again, who are you?  Xah Lee?  And?  I
 didn't subscribe to read reviews on Ruby.  And I'm pretty sure anyone
 that bothers to subscribe to a group about programming has the
 wherewithal to research a language themselves and come to their own
 determiniation.

 Also, this is a Python group and not Ruby.  I knew I should have
 avoided this post and read the one about Nike Shoes from China.  At
 least those bits of trolling spam don't try to mask themselves as
 something worthwhile.

agree with you.

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


Re: Ideas to optimize this getitem/eval call?

2009-01-03 Thread Steven D'Aprano
On Sat, 03 Jan 2009 04:14:14 -0800, mario wrote:

 On Jan 3, 7:16 am, Steven D'Aprano st...@remove-this-
 cybersource.com.au wrote:
[...]
 I must say though, your choice of builtins to prohibit seems rather
 arbitrary. What is dangerous about (e.g.) id() and isinstance()?
 
 Preventive, probably. I also feel that temlates should have any business
 with info such as the memory addressed returnred by id(). For
 isinstance, becuase it is somewhat related to __subclasses__ that is
 known to be insecure.

It's that probably that worries me.

In my earlier post, I was going to say your choice of builtins to 
prohibit seems rather Cargo Cult-ish, but I decided that might be a bit 
rude, and I decided to give you the benefit of the doubt. But your answer 
here doesn't really give me any more confidence.

What security issues do you think you are preventing by prohibiting id()? 
It is true that the id returned is a memory address in CPython, but 
that's a mere implementation detail, and may not be true in other 
implementations. Even if it is a memory address, so what? You can't do 
anything with it except treat it as an integer. I don't see how id() 
decreases security one iota.

In the absence of even a theoretical threat, banning a function that 
returns an int because the int is derived from a memory address (but 
can't be used as one!) makes you appear to be engaging in Cargo Cult 
programming: following the ritual, without any understanding of what you 
are doing.

http://catb.org/~esr/jargon/html/C/cargo-cult-programming.html

Sorry to be so harsh, especially over such a tiny little thing as the 
id() function, but that's the impression it gives me, and I'm probably 
not the only one. It is true that a false positive (needlessly banning a 
harmless function) has less serious consequences than a false negative 
(failing to ban a harmful function), but it does reduce confidence that 
you know what you're doing.

Likewise for isinstance() and issubclass(). They may be related to 
__subclasses__, but they don't give the caller access to __subclassess__. 
So what is the actual threat you are defending against?

I'm not saying that there must be an actual in-the-wild demonstrated 
vulnerability before you prohibit a built-in, but there should be at 
least a plausible attack vector.


 
 Incidentally, I updated the page you point to clarify what is going on.

Speaking of that page, you have an obvious typo (teh instead of the) 
that should be fixed:

In addition to teh above, all subclasses of BaseException...

http://evoque.gizmojo.org/usage/restricted/




 I also added a link to Brett Cannon's inspiration paper on the topic of
 securing the python interpreter...
 
      except:
          # KeyError, NameError, AttributeError, SyntaxError, #
          ValueError, TypeError, IOError

 If you want to capture seven exceptions, then capture seven exceptions,
 not any exception.
 
 Absolutely not. I want to catch ALL evaluation exceptions...

I see. It wasn't clear that this was deliberate, I read it as if there 
was a fixed, finite list you wanted to catch, and nothing else. You 
should make sure this is clearly documented in your code.



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


Re: strange behavior of math.sqrt() in new 3.0 version

2009-01-03 Thread Eric Kemp

Tim Roberts wrote:

Scott David Daniels scott.dani...@acm.org wrote:

I avoid using single-letter variables except where I know the types
from the name (so I use i, j, k, l, m, n as integers, s as string,
and w, x, y, and z I am a little looser with (but usually float or
complex).


It's amazing to me that Fortran continues to live on in the hearts and
minds of today's programmers.


Fortran is alive and well.  If you can find a Fortran 2003 compiler, you 
can even use classes.

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


Re: When does python 3.1, 3.2 version out?

2009-01-03 Thread Benjamin
On Jan 3, 8:47 pm, 叮叮当当 guoti...@gmail.com wrote:
 Now, the 3.0 version is out for a time.

 I wonder when the python 3.1 is out, and what change is in python 3.1.

There's no schedule yet. Hopefully, one will come into being around
PyCon.

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


simple turn-based multiplayer game via TCP server/client

2009-01-03 Thread greyw...@gmail.com
Hi everyone,

I'm learning python to get a multiplayer roleplaying game up and
running.

I didn't see any simple examples of multiplayer games on the web so I
thought I'd post mine here.  I choose Rock, Paper, Scissors as a first
game to experiment with as the game logic/options are easy to
implement and understand.

Initially, I tried to get the socketserver.TCPServer example in the
Python Docs to work, but couldn't get my game variables into the
handle method of the class MyTCPHandler.  And I didn't know how else
to do it.  I ended up creating my own server  client out of simple
sockets based on the simple echo server  client examples in the
Python Docs.

I also wanted to send chat messages OR game variables back  forth,
but I couldn't figure out how to do the OR, so the basic idea in this
implementation is to send the dictionary 'game' back and forth.  game
dict contains all the gaming variables as well as any chat messages.
The program processes results depending on whether the game is
starting, there's a chat message, or there's a game move.

Finally, in testing, I ran the server in IDLE, but I had to load a
command prompt and switch to c:\python30; then type 'python
rpsmulti.py' for the client every time.  Anyone know how to test
server/client code strictly in IDLE?

Anyway, try it out and let me know how you would improve it.

John R.

# NAME: rpsmulti.py
# DESCRIPTION: rock, paper, scissors game multiplayer game
# AUTHOR: John Robinson
# DATE: 1/3/09
# VERSION: Python 3.0
# TO DO:
#   .server_address instead of HOST, PORT?

import socket
from random import choice
from pickle import dumps, loads
from pprint import pprint

HOST, PORT = localhost,   # defined for now
BUFFSIZE = 1024 # for socket.send  recv commands
BACKLOG = 2 # number of clients supported by
server
SECONDS = 3 # seconds until socket.timeout (not
implemented)
# moves dict to translate 'rps' choice
MOVES = {'r':'Rock',
 'p':'Paper',
 's':'Scissors'}
# outcome dict stores result for all possible scenarios
OUTCOME = {('p','r'): 'win',
   ('r','s'): 'win',
   ('s','p'): 'win',
   ('p','p'): 'draw',
   ('r','r'): 'draw',
   ('s','s'): 'draw',
   ('r','p'): 'lose',
   ('s','r'): 'lose',
   ('p','s'): 'lose'}

def main_menu(game):
 initialize game dict variables  opening screen of the game

game['total'] = 0   # total number of games played
game['won'] = 0 # total games won by player
game['lost'] = 0# total games lost by player
game['drew'] = 0# total games drew by player
game['move'] = ''   # player's move (rps)
game['message'] = ''# player's chat message
game['sentmessage'] = ''# player's previous message
game['start'] = True# setting up the game boolean

print(\tROCK PAPER SCISSORS\n)
if game['name']=='':# if returning to menu don't display
the following
game['name'] = get_name()
print(Welcome +game['name']+. Remember...)
print(Rock smashes scissors! Paper covers Rock! Scissors cuts
paper!\n)
print(1. Play single player game)
print(2. Start two player game)
print(3. Join two player game)
print(4. Quit)
print()
c = safe_input(Your choice? , 1234)
c = int(c)
if c==1:
one_player(game)
elif c==2:
start_two_player(game)
elif c==3:
two_player_join(game)
else:
print('Play again soon.')

def safe_input(prompt, values='abcdefghijklmnopqrstuvwxyz'):
 gives prompt, checks first char of input, assures it meets
given values
default is anything goes 
while True:
i = input(prompt)
try:
c = i[0].lower()
except IndexError:  # the only possible error?!
if c=='':
print(Try again.)
else:
if c not in values: # some other character
print(Try again.)
else:   # looks good. continue.
break
return i

def get_name():
 returns input as name 
while True:
name = input(What is your name? )
check = input(name + . Correct (y/n)? )
if check[0] in 'yY':
break
return name

def get_result(player, opponent):
 reports opponent's choice;
checks player and opponent dicts ['move'] against OUTCOME
dict;
reports result
returns player dict with updated values 
print(opponent['name'], 'chose %s.' % (MOVES[opponent['move']]))
# check lookout dict (OUTCOME dictionary)
result = OUTCOME[(player['move'], opponent['move'])]
# update game variables
player['total'] += 1
if result=='win':
print('%s beats %s. You win.' % (MOVES[player['move']], MOVES
[opponent['move']]))
player['won'] += 1
elif result=='draw':
print('%s - %s: no one wins. You draw.' % (MOVES[player

Re: win32gui

2009-01-03 Thread Tim Roberts
Gandalf goldn...@gmail.com wrote:

I'm trying to capture the text word under the user cursor,
so I was searching the win32 lib for functions I can use.

You should know that, in the general case, this is impossible.  Remember
that the screen image you are looking at is just a big array of dots.  If
the window underneath happens to be an image, there won't be any text to
fetch.

Now, in many cases it IS possible, but it's not easy.

i used this to fined the controller under the cursor
win32gui.WindowFromPoint(win32gui.GetCursorPos())
 to get the controller,

That's the first step.  Then, you need to figure out what kind of window it
is.  If it is a standard edit box, you can use the EM_GETLINE functions. If
it's a rich text edit box, you can use the rich text messages.
-- 
Tim Roberts, t...@probo.com
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Port of python stdlib to other languages.

2009-01-03 Thread vk
 AFAIK not. You could try elmer
Elmer looks very interesting, but not really what I was getting at.

 What do you need C for anyway? Or, to put it the other way round - why
 not expose whatever you need in C as python extension, and write your
 app in Python?

I'm not looking to write a Python app atm.

Just curious if someone had started a project like this, to, say, make
Python users more comfortable using other languages (for whatever
reason),
or allow other people to try python-like code in their language to
see
if it suits them.

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


Re: Doubt on creating threads

2009-01-03 Thread koranthala
On Jan 4, 4:59 am, Bryan Olson fakeaddr...@nowhere.org wrote:
 koranth...@gmail.com wrote:
  I am creating an application and it creates ~1-2 threads every second
  and kill it within 10 seconds. After reading this I am worried. Is
  creating a thread a very costly operation?

 Compared to a procedure call it's expensive, but a couple threads per
 second is insignificant. My out-dated Pentium 4 desktop can create and
 destroy a few thousand threads per second under WinXP; more under recent
 Linux.

 --
 --Bryan

Thank you very much.
I was worried about this a lot.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Port of python stdlib to other languages.

2009-01-03 Thread Mensanator
On Jan 3, 10:15�pm, vk vmi...@gmail.com wrote:
  AFAIK not. You could try elmer

 Elmer looks very interesting, but not really what I was getting at.

  What do you need C for anyway? Or, to put it the other way round - why
  not expose whatever you need in C as python extension, and write your
  app in Python?

 I'm not looking to write a Python app atm.

 Just curious if someone had started a project like this, to, say, make
 Python users more comfortable using other languages (for whatever
 reason),
 or allow other people to try python-like code in their language to
 see
 if it suits them.

But wouldn't your language of choice first have to support
things like lists, generators, etc.? I can use GMP library
in C instead of gmpy in Python, but not if I need to use
Python things that I don't know how to implement in C.
--
http://mail.python.org/mailman/listinfo/python-list


Memoizing and WeakValueDictionary

2009-01-03 Thread Paul McGuire
Just wanted to share some experience I had in doing some memory and
performance tuning of a graphics script.  I've been running some long-
running scripts on high-resolution images, and added memoizing to
optimize/minimize object creation (my objects are immutable, so better
to reuse objects from a cache than constantly create and discard
instances).  This helped my script early on, but as the data files got
larger and larger, and runs got longer and longer, the object memoize
cache started to suck up some serious memory, and performance started
to degrade for a different reason - low memory - page thrashing -
program crawling.

It occurred to me that in my program, a given object may get used for
a while, but once its use declines, it doesn't come back for a while.
At first blush, I thought about using some sort of LRU cache, but
first I tried the WeakValueDictionary from the wkref module.  This
worked great!

Now I get fairly optimal reuse of my immutable instances, but my
object cache doesn't grow without bounds.

Does this sound like a correct interpretation of this behavior?  If
so, it would seem that WeakValueDictionary would be a good
recommendation to go along with any memoizing implementations.
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple turn-based multiplayer game via TCP server/client

2009-01-03 Thread alex goretoy
Since we are on the subject of Rock, Paper, Scissors. I've recntly watched
this one video on how to make a .deb out of .py files and the tutor was
using a rock, paper scissors game.

Not sure how this may come of use to you but, I'll post it anyway for you to
look at. May help somehow.

http://www.google.com/search?hl=enq=filetype%3Apy+%22rock+paper+scissors%22btnG=Search

http://www.showmedo.com/videos/video?name=linuxJensMakingDebfromSeriesID=37


Hope this help you in your journey for multiplayer game somehow

On Sun, Jan 4, 2009 at 3:58 AM, greyw...@gmail.com greyw...@gmail.comwrote:

 Hi everyone,

 I'm learning python to get a multiplayer roleplaying game up and
 running.

 I didn't see any simple examples of multiplayer games on the web so I
 thought I'd post mine here.  I choose Rock, Paper, Scissors as a first
 game to experiment with as the game logic/options are easy to
 implement and understand.

 Initially, I tried to get the socketserver.TCPServer example in the
 Python Docs to work, but couldn't get my game variables into the
 handle method of the class MyTCPHandler.  And I didn't know how else
 to do it.  I ended up creating my own server  client out of simple
 sockets based on the simple echo server  client examples in the
 Python Docs.

 I also wanted to send chat messages OR game variables back  forth,
 but I couldn't figure out how to do the OR, so the basic idea in this
 implementation is to send the dictionary 'game' back and forth.  game
 dict contains all the gaming variables as well as any chat messages.
 The program processes results depending on whether the game is
 starting, there's a chat message, or there's a game move.

 Finally, in testing, I ran the server in IDLE, but I had to load a
 command prompt and switch to c:\python30; then type 'python
 rpsmulti.py' for the client every time.  Anyone know how to test
 server/client code strictly in IDLE?

 Anyway, try it out and let me know how you would improve it.

 John R.

 # NAME: rpsmulti.py
 # DESCRIPTION: rock, paper, scissors game multiplayer game
 # AUTHOR: John Robinson
 # DATE: 1/3/09
 # VERSION: Python 3.0
 # TO DO:
 #   .server_address instead of HOST, PORT?

 import socket
 from random import choice
 from pickle import dumps, loads
 from pprint import pprint

 HOST, PORT = localhost,   # defined for now
 BUFFSIZE = 1024 # for socket.send  recv commands
 BACKLOG = 2 # number of clients supported by
 server
 SECONDS = 3 # seconds until socket.timeout (not
 implemented)
 # moves dict to translate 'rps' choice
 MOVES = {'r':'Rock',
 'p':'Paper',
 's':'Scissors'}
 # outcome dict stores result for all possible scenarios
 OUTCOME = {('p','r'): 'win',
   ('r','s'): 'win',
   ('s','p'): 'win',
   ('p','p'): 'draw',
   ('r','r'): 'draw',
   ('s','s'): 'draw',
   ('r','p'): 'lose',
   ('s','r'): 'lose',
   ('p','s'): 'lose'}

 def main_menu(game):
 initialize game dict variables  opening screen of the game
 
game['total'] = 0   # total number of games played
game['won'] = 0 # total games won by player
game['lost'] = 0# total games lost by player
game['drew'] = 0# total games drew by player
game['move'] = ''   # player's move (rps)
game['message'] = ''# player's chat message
game['sentmessage'] = ''# player's previous message
game['start'] = True# setting up the game boolean

print(\tROCK PAPER SCISSORS\n)
if game['name']=='':# if returning to menu don't display
 the following
game['name'] = get_name()
print(Welcome +game['name']+. Remember...)
print(Rock smashes scissors! Paper covers Rock! Scissors cuts
 paper!\n)
print(1. Play single player game)
print(2. Start two player game)
print(3. Join two player game)
print(4. Quit)
print()
c = safe_input(Your choice? , 1234)
c = int(c)
if c==1:
one_player(game)
elif c==2:
start_two_player(game)
elif c==3:
two_player_join(game)
else:
print('Play again soon.')

 def safe_input(prompt, values='abcdefghijklmnopqrstuvwxyz'):
 gives prompt, checks first char of input, assures it meets
 given values
default is anything goes 
while True:
i = input(prompt)
try:
c = i[0].lower()
except IndexError:  # the only possible error?!
if c=='':
print(Try again.)
else:
if c not in values: # some other character
print(Try again.)
else:   # looks good. continue.
break
return i

 def get_name():
 returns input as name 
while True:
name = input(What is your name? )
check = input(name + . Correct (y/n)? )
if check[0] in 'yY':
break
return name

 def 

Re: why cannot assign to function call

2009-01-03 Thread Steven D'Aprano
I'm answering both John and Aaron's comments in the following. Mostly 
John at the start, Aaron toward the end.


On Sat, 03 Jan 2009 15:42:47 -0800, Aaron Brady wrote:

 On Jan 3, 11:25 am, John O'Hagan resea...@johnohagan.com wrote:

[...]

  According to this, when you replace every floorboard on a porch, one
  at a time, it's still the same porch-- it's changed, it's different,
  and it's the same.  However, if you haul off the porch and put a new
  one in its place, it's not.  ('porch[:]=' vs. 'porch='.)  You can't
  just look at the initial and final configurations of matter to
  determine so.  Therefore, 'id' is an informal function.
  
  This analogy describes the ontological minefield I was referring to
  in a previous post in this thread (which has expired in my mail
  reader, so my apologies if the threading goes awry): In what sense is
  a porch (or list, or string) the same if all (or even some of) its
  parts have been exchanged?
  
  I think the answer is something to do with the abstraction, the
  container, the instance of the class. 

That seems reasonable. When you say alist[:] = [1, 2, 3] the container 
remains the same, while the contents change.


  Would it be fair to say that perhaps there are no
  truly mutable objects, only immutable containers whose contents (also
  immutable objects themselves) may be exchanged? Or to pose the
  question another way, are objects only mutable insofar as they are
  composite?

That depends on what you mean by composite. Everything is composite in 
some sense, even a single bit in memory has a physical reality made of 
atoms with magnetic fields. But taken as an abstract entity, it is 
reasonable to treat a single bit as an atomic non-composite thing, and a 
single bit is mutable.

In practice, actual Python objects tend to be mutable only if they are 
composite (although being composite doesn't make them mutable -- consider 
frozen sets and tuples). In principle, this is not necessary. There's no 
reason why Python couldn't expose a single bit as a data type, so you 
could write this:

 n = bit(1)
 bool(n)
True
 n.flip()
 bool(n)
False


  As you argue above, the planks are not the porch; I would add that
  it's your _decision_ to build (or tear down) a porch which makes it
  _that_  particular porch (or not).

No, there's no such decision needed. Perhaps a hurricane comes through 
and rips the porch up. Maybe a rogue television crew comes by while 
you're at work and renovates your house without your knowledge.

The lack of decision-making needed is more obvious when you consider 
something like a fast-flowing river. The specific water molecules making 
up the river at any particular instant in time flow away in a matter of 
days or weeks, but rivers have a continuity of existence measured in 
thousands of years. I trust that nobody is going to argue that the river 
makes any decisions at all?


  As you imply above (I think), you have to keep looking (or someone
  does, presumably the interpreter) to know whether an object is the
  same as or just equal to another (which starts to sound spookily like
  the role of the observer in phenomenology or quantum physics).

No, I think you're introducing mysticism here that isn't needed. A bit 
like quantum mechanics, really :)

In Python, every object has an identity and a value. If objects X and Y 
have the same identity, they are the same object. If X is the object with 
id 1234, and Y is the object with id 1234, then both are the same object. 
If their ids are different, then they are not.

In CPython, the id is given by the memory location of the object, which 
leads to a very intuitive understanding of same: the object with id 
1234 is at memory location 1234, and since there can only be one object 
at a particular memory location at a time, obviously all objects with id 
1234 must be the same object (provided they exist simultaneously).

(To be pedantic, there can't actually be objects [note plural] existing 
simultaneously with the same id. There can only be multiple references to 
the one object.)

In Python implementations where the id is not a memory address 
(IronPython and Jython I think?) the above remains true, even though 
there isn't the simple intuitive picture of only one object can be at a 
specific memory address. Python guarantees that the id is *something* 
which is guaranteed to be unique over the lifetime of every object.

Actually, our intuition about one thing per place at the one time is not 
strictly correct. Consider the memory address 1234, which currently has 
the value in hex of 0x58. That byte may be the numeric value 88, the 
ASCII char X, the set of flags 1011000, or any other thing, depending 
on what interpretation we give to it. What a thing is is actually a 
more difficult question than it appears at first glance.

[...]

 I think the key ingredient is that there's no such thing as side
 effect in math.

I don't see that this is relevant. We're not talking about 

Re: Testing if an index is in a slice

2009-01-03 Thread ajaksu
On Jan 3, 8:53 pm, Bryan Olson fakeaddr...@nowhere.org wrote:
 If we add a parameter for the length of the list to which the slice is
 applied, then inslice() is well-defined.

Cool!

 I thought it would easy to write,

Heh, I gave up on the example I mentioned above :)

 but that was hours ago when I knew
 less about Python slice indexing than I do now. And I thought I new a
 bunch from writing a virtual slice class.

Maybe you could write about what you learned in the docs?

 I'm leaning towards mmanns' idea that this should be built in. Handling
 all the cases is remarkably tricky.

Even without testing your code, I agree. I suggest that you add this
as a feature request to the tracker at http://bugs.python.org/. I hope
Raymond Hettinger likes it and adds an islice version :)
--
http://mail.python.org/mailman/listinfo/python-list


[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Pavel Kosina

Pavel Kosina g...@post.cz added the comment:

You can open script made in python 2.x and it stops immediately working
after saving, if it is coding-aware. You can have bigger project and use
idle for editing config and text files from this project too. It is
unfair to change without notification the encodings. Or do you
consider IDLE just for beginners for learning?

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Pavel Kosina

Pavel Kosina g...@post.cz added the comment:

I forgot about Perhaps IDLE should offer to convert it on opening.
That would be nice, too.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Martin v. Löwis

Martin v. Löwis mar...@v.loewis.de added the comment:

Here is a patch to provide an explicit message that the file will be
converted when the file is opened (also querying what encoding should be
converted from), answering the complaint that the conversion is without
notice.

If you want to edit Python 2.x scripts with IDLE 3, you need to add
encoding declarations to the files. For bigger projects, it is
reasonable to expect that they do add these declarations.

Again, please only report one issue at the time. You chose to make
Python source files the topic of this issue, so please don't divert into
config or text files.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Pavel Kosina

Pavel Kosina g...@post.cz added the comment:

Sorry, where is the patch?

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Martin v. Löwis

Changes by Martin v. Löwis mar...@v.loewis.de:


--
keywords: +patch
Added file: http://bugs.python.org/file12561/conv.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Martin v. Löwis

Changes by Martin v. Löwis mar...@v.loewis.de:


--
keywords: +needs review
priority:  - release blocker

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4796] Decimal to receive from_float method

2009-01-03 Thread Raymond Hettinger

Changes by Raymond Hettinger rhettin...@users.sourceforge.net:


--
assignee: rhettinger - marketdickinson
keywords: +needs review -patch
Added file: http://bugs.python.org/file12562/decimal2.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4796
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4796] Decimal to receive from_float method

2009-01-03 Thread Raymond Hettinger

Changes by Raymond Hettinger rhettin...@users.sourceforge.net:


Removed file: http://bugs.python.org/file12558/decimal.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4796
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Pavel Kosina

Pavel Kosina g...@post.cz added the comment:

OK, I got it. 

In my opinion it would nice if user can either convert file to utf8 or
to do nothing and add new encodings declaration or cancel. Current
Cancel gives an Decoding error. If you give an encodings that doesn't
exist, it shouldn't  destroy IDLE. Hoping its not my mistake, cause I do
not have all files from 3.1a  - just those from idlelib.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4796] Decimal to receive from_float method

2009-01-03 Thread Mark Dickinson

Mark Dickinson dicki...@gmail.com added the comment:

Instead of the repeated divisions and Inexact tests, how about a direct 
approach:  n/2**k = (n*5**k)/10**k, so something like:

sign = 0 if copysign(1.0, self) == 1.0 else 1
n, d = abs(self).as_integer_ratio()
k = d.bit_length() - 1
return _dec_from_triple(sign, str(n*5**k), -k)

should work, and would likely be faster too.

I also think the sign of 0 should be preserved:  i.e.,

 Decimal.from_float(-0.0)
Decimal('-0')

Am still reviewing---more comments to come.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4796
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4816] Patch of itertools.{combinations, permutations} for empty combinations

2009-01-03 Thread Thomas Finley

New submission from Thomas Finley tfin...@gmail.com:

This is a patch for the Python 3.1 build checked out from
http://svn.python.org/projects/python/branches/py3k

The current behavior of itertools.combinations(iterable,r) and
itertools.permutations(iterable,r) is to throw a ValueError if iterable
yields fewer than r items.  This changes these functions so the
generator instead yields 0 items.

As for my argument for acceptance, while the original behavior is not a
bug insofar as its implementation was deliberate, I'd argue this is
undesirable on grounds of mathematical consistency and functionality.

In mathematics the choose function is defined as (n choose r)=0 for
rn, so itertools.combinations' behavior is inconsistent with its
obvious combinatorial analogy.  (Similar for permutations and the
combinatorial P function.)

For functionality I'll cite my own case as anecdote.  In writing
regression tests I wanted to ensure that a group of items obeyed a
certain mutually consistent property between all triples.  (Something
akin to the triangle inequality.)  So:

all(triangle_respected(*triple) for triple in
itertools.combinations(group, 3))

If len(group)=2, that's fine, since with no triangles there is no
inconsistency, and all(())==True.  However, the code failed with a
ValueError when groups were that small.  Working around this was fairly
awkward, since I wanted to continue to fail noisily if my
triangle_respected function threw a ValueError, and I wasn't sure at all
that it wouldn't if my items were 

The patch modifies Modules/itertoolsmodule.c slightly, changing
combinationsobject_new and permutationsobject_new.  (Deleting the error
throwing code, and have one line changes in both structures to handle
the nr case.  One could handle this special case more efficiently than
I do by not bothering to allocate certain structures in this case, but I
didn't want to tempt fate.)  The patch also changes the appropriate
tests in Lib/test/test_itertools.py .

Obviously, this would break code that depends upon Python throwing
ValueError in the event of the combination or permutation sequence being
empty.  However, I hope given that combinations and permutations are a
relative novelty that their behavior in this corner case is not yet
etched in stone.

Sorry if this belongs in a PEP -- it seems quite minor, but I don't
quite have a feel what the threshold is.

--
components: Library (Lib), Tests
files: itertools-empty-combinations.diff
keywords: patch
messages: 78943
nosy: TFinley
severity: normal
status: open
title: Patch of itertools.{combinations,permutations} for empty combinations
type: behavior
versions: Python 3.1
Added file: http://bugs.python.org/file12563/itertools-empty-combinations.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4816
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4608] urllib.request.urlopen does not return an iterable object

2009-01-03 Thread Jakub Wilk

Jakub Wilk uba...@users.sf.net added the comment:

Oops, __next__ is OK. Sorry for the confusion.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4608
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4817] PyOS_GetLastModificationTime is unused

2009-01-03 Thread Ulrich Eckhardt

New submission from Ulrich Eckhardt eckha...@satorlaser.com:

This is just to record that the above function is wrongly documented,
inconsistently implemented, but fortunately unused, so it can be removed.

In addition to the patch attached, there are two files that can be removed:
Python/getmtime.c
RISCOS/Python/getmtime_riscos.c

--
components: Interpreter Core
files: python-2.7-eradicate-getmtime.0.patch
keywords: patch
messages: 78945
nosy: eckhardt
severity: normal
status: open
title: PyOS_GetLastModificationTime is unused
type: resource usage
versions: Python 2.7
Added file: 
http://bugs.python.org/file12564/python-2.7-eradicate-getmtime.0.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4817
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4751] Patch for better thread support in hashlib

2009-01-03 Thread ebfe

Changes by ebfe knabberknusperh...@yahoo.de:


Removed file: http://bugs.python.org/file12557/md5module_small_locks.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4751
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4796] Decimal to receive from_float method

2009-01-03 Thread Mark Dickinson

Mark Dickinson dicki...@gmail.com added the comment:

A couple more things:

1. There's a typo 'equilvalent' in the decimal.py part of the patch.

2. Can I suggest using

return d._fix(self)

instead of 

return self.plus(d)

in create_decimal_from_float.  The plus method does two things: rounds 
to the current context *and* converts -0.0 to 0.0; we only want the 
first of these.

(It's always been a source of mild irritation to me that there's no 
public method for simply rounding a Decimal to a given context---i.e., a 
public equivalent of _fix.)

--
assignee: marketdickinson - rhettinger

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4796
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4818] Patch for thread-support in md5module.c

2009-01-03 Thread ebfe

New submission from ebfe knabberknusperh...@yahoo.de:

Here is another patch, this time for the fallback-md5-module. I know
that situations are rare where openssl is not present but threading is.
However they might occur out there and the md5module needed some love
anyway:

- The MD5 class from the fallback module can now also use threads with
'small locks'
- The behaviour regarding unicode data input is now consistent as to
what the openssl-driven classes do.
- Some code cleanup.


I might act on the sha modules as way the next days. sha256.c still
accepts 's#'...


Also see issue #4751

--
files: md5module_small_locks.diff
keywords: patch
messages: 78947
nosy: ebfe
severity: normal
status: open
title: Patch for thread-support in md5module.c
Added file: http://bugs.python.org/file12565/md5module_small_locks.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4818
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Martin v. Löwis

Martin v. Löwis mar...@v.loewis.de added the comment:

 In my opinion it would nice if user can either convert file to utf8 or
 to do nothing and add new encodings declaration or cancel.

Ypu can still add an encoding declaration after the file got converted.
Cancelling is also possible.

 If you give an encodings that doesn't exist, it shouldn't  destroy IDLE.

Right. Here is a patch that fixes that.

Added file: http://bugs.python.org/file12566/conv.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4815] idle 3.1a1 utf8

2009-01-03 Thread Martin v. Löwis

Changes by Martin v. Löwis mar...@v.loewis.de:


Removed file: http://bugs.python.org/file12561/conv.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4815
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4818] Patch for thread-support in md5module.c

2009-01-03 Thread Martin v. Löwis

Martin v. Löwis mar...@v.loewis.de added the comment:

ebfe, please identify yourself with a real name; please also sign a
contributor form.

--
nosy: +loewis

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4818
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4812] Junk in the decimals namespace

2009-01-03 Thread Mark Dickinson

Mark Dickinson dicki...@gmail.com added the comment:

Done (r68191 through r68194).

--
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4812
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4816] Patch of itertools.{combinations, permutations} for empty combinations

2009-01-03 Thread Mark Dickinson

Mark Dickinson dicki...@gmail.com added the comment:

I agree that the proposed behaviour seems more correct:  the collection of 
all subsets of size 4 of range(3) is perfectly valid and well-defined;  it 
just happens to be empty.  I've also encountered this in practice (in code 
that was enumerating partitions of a list into a fixed number of pieces), 
but in my case it was easier to work around.

I guess the counterargument is that the current ValueError might catch 
bugs early;  I don't know how often this is true in practice.

In any case, this is Raymond's call.

--
assignee:  - rhettinger
nosy: +marketdickinson, rhettinger

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4816
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4751] Patch for better thread support in hashlib

2009-01-03 Thread ebfe

ebfe knabberknusperh...@yahoo.de added the comment:

Haypo, we can probably reduce overhead by defining ENTER_HASHLIB like this:

#define ENTER_HASHLIB(obj) \
if ((obj)-lock) { \
if (!PyThread_acquire_lock((obj)-lock, 0)) { \
Py_BEGIN_ALLOW_THREADS \
PyThread_acquire_lock((obj)-lock, 1); \
Py_END_ALLOW_THREADS \
} \
}

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4751
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1717] Get rid of more refercenes to __cmp__

2009-01-03 Thread Mark Dickinson

Mark Dickinson dicki...@gmail.com added the comment:

[Georg Brandl, on spark.py]
 This is used by asdl_c.py which generates Python-ast.c -- it should be
 updated.

The only issue here is a single comment, which reads:

#  GenericASTMatcher.  AST nodes must have __getitem__ and __cmp__

Still, I'm reluctant to remove or alter the comment without
understanding why it was there in the first place.  If someone more
familiar with AST stuff can confirm that __cmp__ is definitely no
longer needed, I'll remove the mention of it from the comment.

 Misc/cheatsheet

  This needs a general overhaul.

I'll open a separate issue for this, if that's okay with everyone.  
Presumably 3.0.1 doesn't need to wait for Misc/cheatsheet to be updated.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue1717
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1717] Get rid of more references to __cmp__

2009-01-03 Thread Martin v. Löwis

Changes by Martin v. Löwis mar...@v.loewis.de:


--
title: Get rid of more refercenes to __cmp__ - Get rid of more references to 
__cmp__

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue1717
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4580] slicing of memoryviews when itemsize != 1 is wrong

2009-01-03 Thread Martin v. Löwis

Changes by Martin v. Löwis mar...@v.loewis.de:


--
keywords:  -needs review

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4580
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4580] slicing of memoryviews when itemsize != 1 is wrong

2009-01-03 Thread Martin v. Löwis

Changes by Martin v. Löwis mar...@v.loewis.de:


--
assignee:  - pitrou
resolution:  - accepted

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4580
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4818] Patch for thread-support in md5module.c

2009-01-03 Thread Lukas Lueg

Lukas Lueg knabberknusperh...@yahoo.de added the comment:

Sent the form by fax

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4818
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4819] Misc/cheatsheet needs updating

2009-01-03 Thread Mark Dickinson

New submission from Mark Dickinson dicki...@gmail.com:

Misc/cheatsheet could do with an upgrade, both for the 2.x and 3.x branches.

For 3.x, I guess the changes needed are quite extensive.  I'm not sure
how much needs to be changed or added for 2.x; at a quick
glance, the 'with' statement, the 'x if b else y' construction, and the 
unified try-except-finally are missing.

--
assignee: georg.brandl
components: Documentation
messages: 78955
nosy: georg.brandl, marketdickinson
severity: normal
status: open
title: Misc/cheatsheet needs updating
versions: Python 2.7, Python 3.1

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4819
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4753] Faster opcode dispatch on gcc

2009-01-03 Thread Antoine Pitrou

Antoine Pitrou pit...@free.fr added the comment:

 I'm not an expert in this kind of optimizations. Could we gain more
 speed by making the dispatcher table more dense? Python has less than
 128 opcodes (len(opcode.opmap) == 113) so they can be squeezed in a
 smaller table. I naively assume a smaller table increases the amount of
 cache hits.

I don't think so. The end of the current table, which doesn't correspond
to any valid opcodes, will not be cached anyway. The upper limit to be
considered is the maximum value for a valid opcode, which is 147.
Reducing that to 113 may reduce cache pressure, but only by a tiny bit.

Of course, only experimentation could tell us for sure :)

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4753
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4806] Function calls taking a generator as star argument can mask TypeErrors in the generator

2009-01-03 Thread Hagen Fürstenau

Hagen Fürstenau hfuerste...@gmx.net added the comment:

I'm getting confused about whether it's actually desired behaviour that
generators can be star arguments.

The error message seems to say it's not: argument after * must be a
sequence. The docs seem to agree: If the syntax *expression appears in
the function call, expression must evaluate to a sequence. However
test_extcall specifically tests function calls with (non-sequence)
iterables as star arguments.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4806
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue3638] tkinter.mainloop() is meaningless and crash: remove it

2009-01-03 Thread STINNER Victor

Changes by STINNER Victor victor.stin...@haypocalc.com:


Removed file: http://bugs.python.org/file11200/tkinter_remove_mainloop.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue3638
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



  1   2   >