Re: with open('com1', 'r') as f:

2009-04-04 Thread Lawrence D'Oliveiro
In message <01e842d6$0$20654$c3e8...@news.astraweb.com>, Steven D'Aprano 
wrote:

> Firstly, what you describe is an implementation detail of CPython, not
> Python the language. Jython does not close files as soon as they become
> inaccessible, and IronPython and CLPython may not.

That's a limitation of Java-like virtual machines, which I have no intention 
of condonig.

> Secondly, even in CPython things may not be so simple. Not all file-like
> objects are built-in file objects.

Why is this relevant?

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


Re: Python Goes Mercurial

2009-04-04 Thread Lawrence D'Oliveiro
In message <262497db-d2fd-4217-978c-
fc5571f10...@c11g2000yqj.googlegroups.com>, Michele Simionato wrote:

> If Martin - which is well above the average programmer -
> says that he would need help with Git, I take this as
> meaning that most people would get lost with Git.

I don't feel lost with Git. Does that make me an above-average programmer?

> P.S. the thing I do not understand if why we are moving
> away from Subversion.

Because it's still centralized. That means different developers cannot pursue 
parallel branches on their own, those branches must be represented on the 
server.

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Terry Reedy

Lawrence D'Oliveiro wrote:

In message <91e09eaf-5a25-4a6b-b131-
a5245970b...@f19g2000yqh.googlegroups.com>, gert wrote:


On Apr 4, 12:58 am, Lawrence D'Oliveiro  wrote:


In message <8bc55c05-19da-41c4-
b916-48e0a4be4...@p11g2000yqe.googlegroups.com>, gert wrote:


with open('com1', 'r') as f:
for line in f:
print('line')

Why bother, why not just

for line in open('com1', 'r') :
print line

So its does the same thing as with right ?


Why do you need a with?


Automatic closing and finalizing stuff.


All Python objects are reference-counted.


Nope.  Only in CPython, and even that could change.

Once the file object becomes 
inaccessible, it is automatically closed. Simple.


Even in CPython, that would not be true now is the object became 
involved in or became a dependent of a reference cycle.


Note: I wouldn't do this for files open for writing. I'd prefer to make sure 
those were properly flushed and closed, if only to catch any I/O errors.


tjr

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


Re: Python Goes Mercurial

2009-04-04 Thread Jeroen Ruigrok van der Werven
-On [20090405 06:05], Michele Simionato (michele.simion...@gmail.com) wrote:
>P.S. the thing I do not understand if why we are moving
>away from Subversion. Will all the new features entered
>in 1.5 and 1.6 Subversion is now not so bad as it used to
>be and it has the advantage of being already there and
>familiar to most people.

I don't fully get the whole 'we MUST go DVCS!' meme going around the
Internet either.

There's situations where a centralised system like SVN works and there's
situations where a DVCS works better.

Unfortunately there's a whole group of rabid, zealous proponents of one
system or ther other out there that are quick to denounce any of your
rationale for going with one or the other if it is not their $FAVOURITE_ONE.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
Love conquers all...
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Pythoner",Wish me luck!

2009-04-04 Thread Jeroen Ruigrok van der Werven
-On [20090403 20:35], barisa (bbaj...@gmail.com) wrote:
>my question is : what benefit is using interactive intrepreter ?

Install ipython.

It's an extension wrapper around the interactive shell and allows a lot of
very nice features in additional to the standard shell, such as tab
completion.

The benefit is easily testing code snippets, inspecting the contents of
various variables, modules, classes, and so on.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
I must be cruel, only to be kind...
--
http://mail.python.org/mailman/listinfo/python-list


Re: with open('com1', 'r') as f:

2009-04-04 Thread Steven D'Aprano
On Sun, 05 Apr 2009 15:51:31 +1200, Lawrence D'Oliveiro wrote:

> All Python objects are reference-counted. Once the file object becomes
> inaccessible, it is automatically closed. Simple.

If only it were so simple.

Firstly, what you describe is an implementation detail of CPython, not 
Python the language. Jython does not close files as soon as they become 
inaccessible, and IronPython and CLPython may not.

Secondly, even in CPython things may not be so simple. Not all file-like 
objects are built-in file objects.

>>> class MyFile(file):
... pass
...
>>> f = MyFile("test", "r")
>>> n = f.fileno()
>>> os.read(n, 1)
'h'
>>> f.close()
>>> os.read(n, 1)
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 9] Bad file descriptor

My file-like object works just like the built-in file object, but now I 
can do this:

>>> f = MyFile("test", "r")
>>> f.attr = f  # make a reference cycle
>>> n = f.fileno()
>>> del f
>>> os.read(n, 5)
'hello'

And lo and behold, the file is *not* automatically closed when f becomes 
inaccessible. I don't believe the garbage collector will free that file 
descriptor, possibly not even when Python exists. But watch this:

>>> os.close(n)  # just to be sure
>>>
>>> from __future__ import with_statement
>>> with MyFile("test", "r") as f:
... n = f.fileno()
... f.attr = f  # make a reference cycle
...
>>> os.read(n, 5)
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 9] Bad file descriptor


The with statement guarantees[1] closing, even if there are other 
references to the file object elsewhere.






[1] Guarantee void if the file system can't actually close the file for 
some reason.


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


Re: How to free /destroy object created by PyTuple_New

2009-04-04 Thread grbgooglefan
On Apr 4, 10:27 pm, Andrew Svetlov  wrote:
> To destroy every python object you need to call Py_DECREF.
> To call python code fron you C thread you need to use pair
> PyGILState_Ensure/PyGILState_Release.

In my case, my C application has multiple threads & they are accessing
a single Python Interpreter which was initialized by 1st main thread.
In that case also, do I need to use PyGILState_Ensure/
PyGILState_Release APIs?

I am not using Python interpreter level threads.

Can I have a Python interpreter per thread so that I won't have issues
of some data inside Python interpreters being gettint accidently
overwritten/ freed by other thread?

Will Py_DECREF release the items set in that tuple using call to
PyTuple_SetItem? Or do I need to separately call Py_DECREF for them
also?
What is correct sequence for calling Py_DECREF & Py_INCREF?
If I dont call Py_DECREF, will that object (PyTuple) not get freeed at
all, causing memory leak?

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


Re: Creating a session in windows to auth to remote machines

2009-04-04 Thread Tim Golden

ericwoodwo...@gmail.com wrote:

Hi,
 I'm trying to auth to remote machines so I can plunder WMI to get
logs and settings and the like.  My script works for most of my
machines because they're all in the same domain and I run the script
as somebody who has enough access to get at this stuff but for
machines off the domain I'm stuck.


Unless I'm missing something here, you can already specify
username etc. with WMI. Just Dispatch on "WbemScripting.SWbemLocator"
and call .ConnectServer. Just in case you haven't already, I
(naturally :) ) recommend my wmi module [1] which wraps a fair bit
of the plumbing for you, including this. Eg,


import wmi

c = wmi.WMI ("some-machine", user="tim", password="password")

for log in c.Win32_NTLogEvent (
 Logfile="Application",
 Type="error"
):
 print log.RecordNumber, log.SourceName, log.Message





[1] http://timgolden.me.uk/python/wmi.html

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


Re: Generators/iterators, Pythonicity, and primes

2009-04-04 Thread Kay Schluehr
> Question: Is there a way to implement this algorithm using generator
> expressions only -- no "yield" statements allowed?

Yes. Avoiding the yield statement is easy but one might eventually end
up with two statements because one has to produce a side effect on the
primes list. However we can use default parameters in lambdas and
finally get a single expression which is a generator expression:

g = (lambda primes = []:
  (n for n in count(2) \
 if
 (lambda n, primes: (n in primes if primes and n<=primes
[-1] \
 else
 (primes.append(n) or True \
 if all(n%p for p in primes if p <= sqrt(n)) \
 else False)))(n, primes)))()

assert g.next() == 2
assert g.next() == 3
assert g.next() == 5
assert g.next() == 7
--
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads

2009-04-04 Thread ericwoodworth
On Apr 5, 12:22 am, a...@pythoncraft.com (Aahz) wrote:
> In article <4b52f7d7-81d5-4141-9385-ee8cfb90a...@l1g2000yqk.googlegroups.com>,
>
>   wrote:
>
> >I'm using queues to talk between these threads so I could certainly
> >put some kind of message on the queue that causes the threads to
> >commit suicide but I'm thinking there's a more built in way to do what
> >I want.  I'm just not sure what it is.
>
> There isn't, you have the right idea about using queues.
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> "Debugging is twice as hard as writing the code in the first place.
> Therefore, if you write the code as cleverly as possible, you are, by
> definition, not smart enough to debug it."  --Brian W. Kernighan

Ok good to know.  I was letting the search for a really cool solution
stop me from rolling out what I think I already know how to do.
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generators/iterators, Pythonicity, and primes

2009-04-04 Thread Miles
On Sat, Apr 4, 2009 at 2:50 PM, John Posner wrote:
> Inspired by recent threads (and recalling my first message to Python
> edu-sig), I did some Internet searching on producing prime numbers using
> Python generators. Most algorithms I found don't go for the infinite,
> contenting themselves with "list all the primes below a given number".
>
> Here's a very Pythonic (IMHO) implementation that keeps going and going and
> going ...:
>
> from itertools import count
> from math import sqrt
>
> def prime_gen():
> """
> Generate all prime numbers
> """
> primes = []
> for n in count(2):
> if all(n%p for p in primes if p < sqrt(n)):
> primes.append(n)
> yield n
>
> The use of all() is particularly nifty (see
> http://code.activestate.com/recipes/576640/). And so is the way in which the
> list comprehension easily incorporates the sqrt(n) optimization.
>
> Question: Is there a way to implement this algorithm using generator
> expressions only -- no "yield" statements allowed?

def prime_gen():
primes = []
return (primes.append(n) or n for n in count(2) if all(n%p for p
in primes if p<=sqrt(n)))

That version is only marginally faster than your original version.
The biggest performance penalty is that the (... for p in primes ...)
generator isn't aborted once p > sqrt(n). Here's a less nifty but much
more efficient version:

def prime_gen():
prime_list = [2]
for p in prime_list: yield p
for n in itertools.count(prime_list[-1] + 1):
for p in prime_list:
if p * p > n:
prime_list.append(n)
yield n
break
elif n % p == 0:
break
else:
raise Exception("Shouldn't have run out of primes!")

When generating the first 1000 primes, this version's approximately 20
times faster; for the first 10,000 primes, ~80x (but still much slower
than a simple Sieve of Eratosthenes).  To make repeated calls faster,
move prime_list = [2] outside the function.

-Miles

P.S. Gmail shows all your messages with a blank body and a text
attachment containing your message; this is perhaps because your
mailer includes an invalid blank Content-disposition header.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads

2009-04-04 Thread Aahz
In article <4b52f7d7-81d5-4141-9385-ee8cfb90a...@l1g2000yqk.googlegroups.com>,
  wrote:
>
>I'm using queues to talk between these threads so I could certainly
>put some kind of message on the queue that causes the threads to
>commit suicide but I'm thinking there's a more built in way to do what
>I want.  I'm just not sure what it is.

There isn't, you have the right idea about using queues.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Goes Mercurial

2009-04-04 Thread Michele Simionato
On Apr 5, 5:49 am, Lawrence D'Oliveiro  wrote:

> Everybody needs help sometime. If you're accustomed to centralized version
> control (CVS and SVN), it probably takes some time to get used to the way
> distributed systems work. It's nothing to be ashamed of.

If Martin - which is well above the average programmer -
says that he would need help with Git, I take this as
meaning that most people would get lost with Git.
Heck, I am getting lost even with SVN!

 Michele Simionato

P.S. the thing I do not understand if why we are moving
away from Subversion. Will all the new features entered
in 1.5 and 1.6 Subversion is now not so bad as it used to
be and it has the advantage of being already there and
familiar to most people.
--
http://mail.python.org/mailman/listinfo/python-list


Re: possible pairings in a set

2009-04-04 Thread Steven D'Aprano
On Sat, 04 Apr 2009 17:42:58 -0700, Ross wrote:

> I'm new to python and I'm trying to come up with a function that takes a
> given number of players in a game and returns all possible unique
> pairings. Here's the code I've come up with so far, but I'm not getting
> the output I'd like to:

Others have already given a solution for Python 2.6, using 
itertools.combinations(). Here's a solution for Python 2.4 and 2.5.

The thing to remember about combinations is that they can be defined 
recursively. To find the combinations of [1, 2, 3, 4] we can do something 
like this: 

Combinations of [1, 2, 3, 4]:
  Start with the first item, 1.
  Combinations are given by [1] + combinations of what's left: [2, 3, 4].

  Combinations of [2, 3, 4]:
Start with the first item, 2.
Combinations are given by [2] + combinations of what's left: [3, 4].

Combinations of [3, 4]:
  Start with the first item, 3.
  Combinations are given by [3] + combinations of what's left: [4].

  Combinations of [4]:
Start with the first item, 4.
Combinations are given by [4] + combinations of what's left: [].

Combinations of []:
  There aren't any, so we're done.


Using that algorithm gives us this function:

def combinations(seq, r=None):
"""Generator returning combinations of items from sequence 
taken  at a time. Order is not significant. If  is not given,
the entire sequence is returned.
"""
if r == None:
r = len(seq)
if r <= 0:
yield []
else:
for i in xrange(len(seq)):
for cc in combinations(seq[i+1:], r-1):
yield [seq[i]]+cc


def all_pairings(players):
return list(combinations(range(players), 2))


> If I were to execute the function with all_pairings(4), I want to get
> the output [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3].


>>> all_pairings(4)
[[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]



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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Lawrence D'Oliveiro
In message <91e09eaf-5a25-4a6b-b131-
a5245970b...@f19g2000yqh.googlegroups.com>, gert wrote:

> On Apr 4, 12:58 am, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>
>> In message <8bc55c05-19da-41c4-
>> b916-48e0a4be4...@p11g2000yqe.googlegroups.com>, gert wrote:
>>
>>> with open('com1', 'r') as f:
>>> for line in f:
>>> print('line')
>>
>> Why bother, why not just
>>
>> for line in open('com1', 'r') :
>> print line
> 
> So its does the same thing as with right ?

Why do you need a with?

> Automatic closing and finalizing stuff.

All Python objects are reference-counted. Once the file object becomes 
inaccessible, it is automatically closed. Simple.

Note: I wouldn't do this for files open for writing. I'd prefer to make sure 
those were properly flushed and closed, if only to catch any I/O errors.

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


Re: Python Goes Mercurial

2009-04-04 Thread Lawrence D'Oliveiro
In message <49d80a4a$0$30643$9b622...@news.freenet.de>, "Martin v. Löwis" 
wrote:

>In message , Lawrence D'Oliveiro wrote:
>
>> Post an example of what you were trying to do, with the exact messages,
>> and we can walk you through it.
> 
> Unfortunately, these are many months ago, and I don't recall the exact
> error messages. I wasn't really asking for help, merely pointing out
> that I dislike git because it makes me ask for help (something I did
> not have to do for CVS or subversion, except for very special cases).

Everybody needs help sometime. If you're accustomed to centralized version 
control (CVS and SVN), it probably takes some time to get used to the way 
distributed systems work. It's nothing to be ashamed of.

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


Killing threads

2009-04-04 Thread ericwoodworth
Hi,
 I'm new to python and even newer to threading and it seems as
though I'm missing something fundamental about threads.  Basically I
have a program that looks like this:

class ThreadOne(threading.Thread):
 while 1:
  do stuff

class ThreadTwo(threading.Thread):
 while 1:
  do other stuff


first = ThreadOne()
second = ThreadTwo()

while 1:
do stuff


The issue that I'm having is...I don't know how to kill this app in
window.  I hit ctrl-c but that only seems to kill one of the threads.
The rest of the app just lingers.  There's got to be a more graceful
way but so far I haven't googled anything up.

I'm using queues to talk between these threads so I could certainly
put some kind of message on the queue that causes the threads to
commit suicide but I'm thinking there's a more built in way to do what
I want.  I'm just not sure what it is.

I'd appreciate it if somebody could point me in the right direction.
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: possible pairings in a set

2009-04-04 Thread Dave Angel



MRAB wrote:

Dave Angel wrote:



Ross wrote:

I'm new to python and I'm trying to come up with a function that takes
a given number of players in a game and returns all possible unique
pairings. Here's the code I've come up with so far, but I'm not
getting the output I'd like to:

def all_pairings(players):
cleanlist = []
for i in range(players):
cleanlist.append(i)
return cleanlist
start = 0
follow = start +1
finallist = []
while follow <= len(cleanlist)-1:
for player in cleanlist:
mini = cleanlist[start],cleanlist[follow]
finallist.append(mini)
follow +=1
start+=1
return finallist

If I were to execute the function with all_pairings(4), I want to get
the output [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]. Instead, I get
[0,1,2,3] with the code I currently have. Can you guys help me out?
Also, if my code is considered ugly or redundant by this community,
can you make suggestions to clean it up?

  
First problem is the return you have in the middle of the function, 
which returns cleanlist.  That's why you're getting [0, 1, 2, 3]


Once you fix that, you'll find you have exceptions in the code where 
cleanlist[follow] doesn't work if follow is equal to 4.


I'm afraid the code is ugly, and therefore hard to understand or 
fix.  Let me suggest an approach, rather than just giving you the 
code.  Why not create a nested for which generates two subscripts 
between 0 and 4, then append only those pairs in which the second is 
strictly greater than the first.  It won't be the quickest, but it 
will be easy to follow.


No while loop, no explicit incrementing of variables, and in fact no 
subscripting of the lists.  Just let them supply their own values.
 cleanlist = range(players) # no need for any loop, 
it's already a list (except in Python 3.0, in which case it's a 
sequence that still works just as well)

 finallist = []
 for i .:
 for j...
  if i
Actually, cleanlist[i] == i, so it's pointless. You can do just:

finallist = []
for i in range(players):
for j in range(i + 1, players):
finallist.append((i, j))

or, using list comprehension:

finallist = [(i, j) for i in range(players) for j in range(i + 1, 
players)]





This looked to me like a homework assignment, or a self-assignment for a 
relative beginner in Python.  So I wanted to outline an approach, not 
provide the absolute optimum answer which might not be understood.  I 
avoided mentioning the itertools.combinations() function because you 
can't learn much from a single function call.  I avoided list 
comprehensions because they are very hard for many inexperienced python 
programmers.


I left the cleanlist in because this approach can be readily generalized 
to taking a list which isn't just a list of numbers.  Add an enumerate 
to each of the for loops, and you can readily produce all the 
combinations of whatever might be in the first list.


I debated with myself using slicing of the list for the nested for (your 
range(i+1, players) is equivalent to a slice), and decided that it would 
be harder to read. .  Clearly my nested loop iterates twice as much on 
the average as is needed, but the if is easier to read for a beginner.


Even for experienced developers, sometimes optimizing too early can make 
it hard to visualize generalizing a function.  If the function took a 
list rather than an upperlimit, it would be much more general, but how 
many could take your list comprehension and turn it into

  def  all_pairings(cleanlist):
return   [ (a, b) for i, a in enumerate(cleanlist) for b in 
cleanlist[i+1:] ]


print all_pairings(range(2,6))
print all_pairings( ("tom", "dick", "harry", "jim") )

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


Re: Generators/iterators, Pythonicity, and primes

2009-04-04 Thread Terry Reedy

John Posner wrote:

Inspired by recent threads (and recalling my first message to Python
edu-sig), I did some Internet searching on producing prime numbers using
Python generators. Most algorithms I found don't go for the infinite,
contenting themselves with "list all the primes below a given number".

Here's a very Pythonic (IMHO) implementation that keeps going and going and
going ...:

from itertools import count
from math import sqrt

def prime_gen():
"""
Generate all prime numbers
"""
primes = []
for n in count(2):
if all(n%p for p in primes if p < sqrt(n)):
primes.append(n)
yield n

The use of all() is particularly nifty (see
http://code.activestate.com/recipes/576640/). And so is the way in which the
list comprehension easily incorporates the sqrt(n) optimization.

Question: Is there a way to implement this algorithm using generator
expressions only -- no "yield" statements allowed?


No.  You refer to the list being build in the code for building the list 
(very cute), which requires that the list be bound to a name at the 
start of the process rather than just when complete (which is never ;-).


tjr

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


Re: Why doesn't StopIteration get caught in the following code?

2009-04-04 Thread Terry Reedy

grocery_stocker wrote:
...

while True:

...i = gen.next()
...print i
...
0
1
4
Traceback (most recent call last):
  File "", line 2, in ?
StopIteration


If you had written

for item in gen: print(i)

then StopIteration from gen would be caught.

One expansion of a for loop is (in the above case)

it = iter(gen) # not needed here, but is for general iterables
try:
  while True:
i = it.next()
print(i) # or whatever the loop body is
except StopIteration:
  pass

In other words, 'for i in iterable' expands to several lines of 
boilerplate code.  It is very useful syntactic sugar.


You left out the try..except part.

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


Re: Python Goes Mercurial

2009-04-04 Thread skip

Martin> I wasn't really asking for help, merely pointing out that I
Martin> dislike git because it makes me ask for help (something I did
Martin> not have to do for CVS or subversion, except for very special
Martin> cases).

In fact, Martin is generally the guy answering the CVS and Subversion
questions.

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
"XML sucks, dictionaries rock" - Dave Beazley
--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame and socket.recv

2009-04-04 Thread Aaron Brady
On Apr 2, 4:13 am, Tim Wintle  wrote:
> On Wed, 2009-04-01 at 18:45 -0700, Aaron Brady wrote:
>
> > My game loop looks like this:
>
> > poll events, get 1 at most
> > send to server
> > wait for server reply
> > render entire frame
>
> The look I'm suggesting is:
>
> poll events
> write to (non-blocking) socket
> render frame
> check non-blocking socket and add events to the event queue
>
> > Yes, I am blocking for the data to come down the network.
> > Unfortunately, if I use any "prediction," I will have to go back and
> > un-render the previous frame, then redraw with the new information.
>
> Sounds like that may have to be re-factored slightly, afraid this is why
> real-time networked games are tough to make.
snip

> a) How much to move etc. is decided based on some real-time solution
> (not on the number of frames). Ideally all movement methods take a
> parameter that is a delta in time. (i.e. 1/40th of a second)
>
> b) That time is the time that is synced across machines - if machine B
> has to put it's timer forward 1/50 of a second, you call all the methods
> above with a timedelta of 1/50 before continuing.

Tim Wintle's link has an interesting illustration of this:

"""
Basic Concepts
The Update Loop

For example, Doom's movement physics looks like "Position +=
PositionIncrment" while Unreal's looks like "Position += Velocity *
DeltaTime". This enables greater frame rate scalability.
"""

... Perhaps you've heard of him.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame and socket.recv

2009-04-04 Thread Aaron Brady
On Apr 2, 5:46 pm, Tim Wintle  wrote:
> On Thu, 2009-04-02 at 06:50 -0700, Aaron Brady wrote:
> > It's just that if you register a collision in between the time that
> > one object has changed its position and momentum, and the time you
> > learn about it, you have to retroactively edit the collision, restore
> > hit points, and recalculate the other object's position and momentum,
> > to name a few.
>
> So it sounds like what you are trying to do is emulate shared RAM
> between the two players!
>
> The problem being that you have to effectively lock the variables on one
> machine while the other one reacts.
>
> I believe the answer normally used is the client-server architecture.
>
> Choose one machine to act as the "server" somehow, then let that control
> the entire game state. Both players pass events to this server method
> (using non-blocking sockets), and render things in the position they
> believe they are in.
>
> I believe that is how all the current RTS games work, certainly how Red
> Alert worked, and is how all FPS games work (e.g. in unreal there is
> always a "server", and in single player mode the clients are simply bots
> and the local client application.)
>
> You might find the docs for Unreal networking (c. 1999) useful to
> explain what they did better than I 
> can.http://unreal.epicgames.com/Network.htm

I don't think you did the link justice in your introduction of it.  I
don't think I did your post justice... by ignoring it.

Here is a quote from the paper:
"""
Player Prediction

This approach is purely predictive, and it gives one the best of both
worlds: In all cases, the server remains completely authoritative.
Nearly all the time, the client movement simulation exactly mirrors
the client movement carried out by the server, so the client's
position is seldom corrected. Only in the rare case, such as a player
getting hit by a rocket, or bumping into an enemy, will the client's
location need to be corrected.
"""

Please excuse me briefly; the FBI is beating down my door for quoting
it.

Regardless, I think it was the 'correction', per se, step that I was
interested in.  Does it suffice to merely wait until recovering from
the lag to notify the player s/he's dead, and proceed normally
otherwise?

Should the keystroke that the player hit during lag be delivered asap,
or 'in time' with how many seconds elapsed since the last known
frame?  My game in particular, I have a hunch, relies on more precise
timing than you might expect in a game.

> So it sounds like what you are trying to do is emulate shared RAM
> between the two players!

No, that's my other project ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Tk Tix GUI documentation & builder overview and tips

2009-04-04 Thread Aahz
[posted & e-mailed]

In article ,
  wrote:
>
>Before starting I spent some effort to find
>a) relevant documentation,
>b) GUI Builders which might help me,
>c) answers to non-obvious questions.
>
>The process took some time and effort so I want to share my findings:

Adding this to wiki.python.org/moin/ would be very welcome!  (You should
probably hunt around a bit to find the best spot.)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module caching

2009-04-04 Thread Aaron Scott
>         req.write(str(lab.game.settings.daemons))
>         del lab.game.settings
>         req.write(str(lab.game.settings.daemons))
>         lab.game.settings = lab.game.InitGame()
>         req.write(str(lab.game.settings.daemons))
>

Sorry, that should have been:

req.write(str(lab.game.game.daemons))
del lab.game.game
try: req.write(str(lab.game.game.daemons))
except: req.write("failed")
lab.game.game = lab.game.InitGame()
req.write(str(lab.game.game.daemons))
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Pythoner",Wish me luck!

2009-04-04 Thread Linuxwell
Thanks everyone,thank you very much!!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: cProfile.py not found.

2009-04-04 Thread skip

Rahul> I need to profile a slow-running code. The problem is I cannot
Rahul> seem to find cProfile.py.

You want cProfile.c (compiled to cProfile.so).

Rahul> I am using Python 2.4.4 (#3, Feb 17 2008, 15:06:10). 

cProfile was new in 2.5, but the code backports with no problem to 2.4.
Just grab it from a 2.5 distro and build/install it.

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
"XML sucks, dictionaries rock" - Dave Beazley
--
http://mail.python.org/mailman/listinfo/python-list


Re: python docs redirect on python.org is old

2009-04-04 Thread Martin v. Löwis
Brandon Craig Rhodes wrote:
> When I visit ...
> 
>http://www.python.org/doc/lib/lib.html
> 
> ... I get redirected to ...
> 
>http://www.python.org/doc/2.5.2/lib/lib.html
> 
> ... which seems a bit old.

That is intentional. Use

http://docs.python.org/library/

instead.

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


Re: possible pairings in a set

2009-04-04 Thread MRAB

Dave Angel wrote:



Ross wrote:

I'm new to python and I'm trying to come up with a function that takes
a given number of players in a game and returns all possible unique
pairings. Here's the code I've come up with so far, but I'm not
getting the output I'd like to:

def all_pairings(players):
cleanlist = []
for i in range(players):
cleanlist.append(i)
return cleanlist
start = 0
follow = start +1
finallist = []
while follow <= len(cleanlist)-1:
for player in cleanlist:
mini = cleanlist[start],cleanlist[follow]
finallist.append(mini)
follow +=1
start+=1
return finallist

If I were to execute the function with all_pairings(4), I want to get
the output [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]. Instead, I get
[0,1,2,3] with the code I currently have. Can you guys help me out?
Also, if my code is considered ugly or redundant by this community,
can you make suggestions to clean it up?

  
First problem is the return you have in the middle of the function, 
which returns cleanlist.  That's why you're getting [0, 1, 2, 3]


Once you fix that, you'll find you have exceptions in the code where 
cleanlist[follow] doesn't work if follow is equal to 4.


I'm afraid the code is ugly, and therefore hard to understand or fix.  
Let me suggest an approach, rather than just giving you the code.  Why 
not create a nested for which generates two subscripts between 0 and 4, 
then append only those pairs in which the second is strictly greater 
than the first.  It won't be the quickest, but it will be easy to follow.


No while loop, no explicit incrementing of variables, and in fact no 
subscripting of the lists.  Just let them supply their own values.
 cleanlist = range(players) # no need for any loop, it's 
already a list (except in Python 3.0, in which case it's a sequence that 
still works just as well)

 finallist = []
 for i .:
 for j...
  if i
Actually, cleanlist[i] == i, so it's pointless. You can do just:

finallist = []
for i in range(players):
for j in range(i + 1, players):
finallist.append((i, j))

or, using list comprehension:

finallist = [(i, j) for i in range(players) for j in range(i + 1, 
players)]

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


Re: Python Goes Mercurial

2009-04-04 Thread Martin v. Löwis
>> I don't like git because it is too difficult for me. In many cases,
>> git would refuse to do operations like updating or local committing,
>> producing error messages I was not able to understand ...
> 
> Post an example of what you were trying to do, with the exact messages, and 
> we can walk you through it.

Unfortunately, these are many months ago, and I don't recall the exact
error messages. I wasn't really asking for help, merely pointing out
that I dislike git because it makes me ask for help (something I did
not have to do for CVS or subversion, except for very special cases).

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


python docs redirect on python.org is old

2009-04-04 Thread Brandon Craig Rhodes
When I visit ...

   http://www.python.org/doc/lib/lib.html

... I get redirected to ...

   http://www.python.org/doc/2.5.2/lib/lib.html

... which seems a bit old.

-- 
Brandon Craig Rhodes   bran...@rhodesmill.org   http://rhodesmill.org/brandon

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


Re: possible pairings in a set

2009-04-04 Thread Dave Angel



Ross wrote:

I'm new to python and I'm trying to come up with a function that takes
a given number of players in a game and returns all possible unique
pairings. Here's the code I've come up with so far, but I'm not
getting the output I'd like to:

def all_pairings(players):
cleanlist = []
for i in range(players):
cleanlist.append(i)
return cleanlist
start = 0
follow = start +1
finallist = []
while follow <= len(cleanlist)-1:
for player in cleanlist:
mini = cleanlist[start],cleanlist[follow]
finallist.append(mini)
follow +=1
start+=1
return finallist

If I were to execute the function with all_pairings(4), I want to get
the output [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]. Instead, I get
[0,1,2,3] with the code I currently have. Can you guys help me out?
Also, if my code is considered ugly or redundant by this community,
can you make suggestions to clean it up?

  
First problem is the return you have in the middle of the function, 
which returns cleanlist.  That's why you're getting [0, 1, 2, 3]


Once you fix that, you'll find you have exceptions in the code where 
cleanlist[follow] doesn't work if follow is equal to 4.


I'm afraid the code is ugly, and therefore hard to understand or fix.  
Let me suggest an approach, rather than just giving you the code.  Why 
not create a nested for which generates two subscripts between 0 and 4, 
then append only those pairs in which the second is strictly greater 
than the first.  It won't be the quickest, but it will be easy to follow.


No while loop, no explicit incrementing of variables, and in fact no 
subscripting of the lists.  Just let them supply their own values.
 cleanlist = range(players) # no need for any loop, 
it's already a list (except in Python 3.0, in which case it's a sequence 
that still works just as well)

 finallist = []
 for i .:
 for j...
  if ihttp://mail.python.org/mailman/listinfo/python-list


Re: Python Goes Mercurial

2009-04-04 Thread Martin v. Löwis
>> I don't like git because it is too difficult for me. In many cases,
>> git would refuse to do operations like updating or local committing,
>> producing error messages I was not able to understand ...
> 
> Post an example of what you were trying to do, with the exact messages, and 
> we can walk you through it.

Unfortunately, these are many months ago, and I don't recall the exact
error messages. I wasn't really asking for help, merely pointing out
that I dislike git because it makes me ask for help (something I did
not have to do for CVS or subversion, except for very special cases).

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


RE: possible pairings in a set

2009-04-04 Thread John Posner
 >> Also, if my code is considered ugly or redundant by this community,
 >> can you make suggestions to clean it up?

Python is pretty mature: if you have a simple, generic problem, the chances
are that someone else has already solved it, packaging the solution in a
library (or "module"). For your job, the "itertools" module includes the
function "combinations":

import itertools
for comb in itertools.combinations([0,1,2,3], 2):
print comb

output:
(0, 1)
(0, 2)
(0, 3)
(1, 2)
(1, 3)
(2, 3)

Note that the output of itertools.combinations() is not a list but an
iterator. If you need the entire list, use the list() function to have the
iterator deliver all the goods at once:

mylist = list(itertools.combinations([0,1,2,3], 2))





E-mail message checked by Spyware Doctor (6.0.0.386)
Database version: 5.12110
http://www.pctools.com/en/spyware-doctor-antivirus/
--
http://mail.python.org/mailman/listinfo/python-list


Re: what does "execfile" mean within profiler output and why does it not have a attached line number

2009-04-04 Thread Robert Kern

On 2009-04-04 18:56, Rahul wrote:

"profile" tells me that most of my runtime was spent in just one part (1.28
sec cumulatively out of 1.29 secs. But what is "execfile"? I don't see this
as a function call with my python code. Also what's the 0 in the snippet:
":0(execfile)"? Isn't there supposed to be a line-number?


It's a builtin function, so it has no filename or line number.

execfile is a function that reads a Python file and executes its code. This is 
almost certainly the execfile call from profile.py itself that is running your 
code. Ignore it.



Looking up "execfile" in the python manual leads me to "exec": "This
statement supports dynamic execution of Python code."

But that seems pretty generic; how can I now try figuring out which part of
my python file is the bottleneck?


To quickly find your hotspots, start by sorting by 'time' (that would be 
displayed as the 'tottime' column in the human-readable output). That tells you 
how much time is spent in each function itself, excluding the time it spends 
calling out to other functions. For example, per the docs under "Instant User’s 
Manual" (which you might want to spend a little more time with):


  p.sort_stats('time').print_stats(10)

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: possible pairings in a set

2009-04-04 Thread Benjamin Peterson
Ross  gmail.com> writes:
> Can you guys help me out?

Do you have Python 2.6? If so, it's a solved problem. :)

import itertools
possible_pairings = list(itertools.combinations(players, 2))




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


Re: what does "execfile" mean within profiler output and why does it not have a attached line number

2009-04-04 Thread John Machin
On Apr 5, 9:56 am, Rahul  wrote:
> "profile" tells me that most of my runtime was spent in just one part (1.28
> sec cumulatively out of 1.29 secs. But what is "execfile"? I don't see this
> as a function call with my python code. Also what's the 0 in the snippet:  
> ":0(execfile)"? Isn't there supposed to be a line-number?
>
> Looking up "execfile" in the python manual leads me to "exec": "This
> statement supports dynamic execution of Python code."
>
> But that seems pretty generic; how can I now try figuring out which part of
> my python file is the bottleneck?
>
> Sorry, I'm a newbiee to profiling.
>
> ##
>        51651 function calls (37762 primitive calls) in 1.290 CPU seconds
>  ncalls  tottime  percall  cumtime  percall filename:lineno(function)
> [snip]
>     1    0.010    0.010    1.280    1.280 :0(execfile)
> [snip]
> ##

That means no more than "the profiler executed all of your code
once, it took 0.01 seconds inside the execfile itself, 0.01 seconds
per execution, total time spent by the execfile *and* what it called
was 1.28 seconds ("cum" == "cumulative"), again 1.28 secs per
execution"

So ignore that and look at the figures for the app functions/methods.
--
http://mail.python.org/mailman/listinfo/python-list


possible pairings in a set

2009-04-04 Thread Ross
I'm new to python and I'm trying to come up with a function that takes
a given number of players in a game and returns all possible unique
pairings. Here's the code I've come up with so far, but I'm not
getting the output I'd like to:

def all_pairings(players):
cleanlist = []
for i in range(players):
cleanlist.append(i)
return cleanlist
start = 0
follow = start +1
finallist = []
while follow <= len(cleanlist)-1:
for player in cleanlist:
mini = cleanlist[start],cleanlist[follow]
finallist.append(mini)
follow +=1
start+=1
return finallist

If I were to execute the function with all_pairings(4), I want to get
the output [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]. Instead, I get
[0,1,2,3] with the code I currently have. Can you guys help me out?
Also, if my code is considered ugly or redundant by this community,
can you make suggestions to clean it up?
--
http://mail.python.org/mailman/listinfo/python-list


Re: cProfile.py not found.

2009-04-04 Thread Rahul
John Machin  wrote in news:0a8400dc-b14b-4bb9-a608-
7327fe88a...@j18g2000prm.googlegroups.com:

> Read the fantastic manual:
> 
> http://docs.python.org/library/profile.html
 [snip]
>   cProfile is recommended for most users; it's a C extension with
> reasonable overhead that makes it suitable for profiling long-running
> programs. Based on lsprof, contributed by Brett Rosen and Ted Czotter.
> 
>   New in version 2.5.
> 

Thanks John; I did read the manual which is why I decided to use cProfile 
as it was "recommended for most users".  I missed the last bit about "New 
in version 2.5." 

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


what does "execfile" mean within profiler output and why does it not have a attached line number

2009-04-04 Thread Rahul
"profile" tells me that most of my runtime was spent in just one part (1.28 
sec cumulatively out of 1.29 secs. But what is "execfile"? I don't see this 
as a function call with my python code. Also what's the 0 in the snippet:  
":0(execfile)"? Isn't there supposed to be a line-number? 

Looking up "execfile" in the python manual leads me to "exec": "This 
statement supports dynamic execution of Python code."

But that seems pretty generic; how can I now try figuring out which part of 
my python file is the bottleneck? 

Sorry, I'm a newbiee to profiling.


##
   51651 function calls (37762 primitive calls) in 1.290 CPU seconds
 ncalls  tottime  percall  cumtime  percall filename:lineno(function)
[snip]
10.0100.0101.2801.280 :0(execfile)
[snip]
##




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


Re: cProfile.py not found.

2009-04-04 Thread Rahul
John Machin  wrote in news:4c8ee09e-71e2-464a-a3c0-
b630b4707...@c18g2000prh.googlegroups.com:

> Looks like our definitions of "read" differ :-)
> 

Sorry. I ought to have said "skimmed" :) 

I guess I am one of those guilty lazy-bums that the manual refers to under 
<<>>

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


Re: cProfile.py not found.

2009-04-04 Thread John Machin
On Apr 5, 9:41 am, Rahul  wrote:
> John Machin  wrote in news:0a8400dc-b14b-4bb9-a608-
> 7327fe88a...@j18g2000prm.googlegroups.com:
>
>
>
> > Read the fantastic manual:
>
> >http://docs.python.org/library/profile.html
>  [snip]
> >       cProfile is recommended for most users; it's a C extension with
> > reasonable overhead that makes it suitable for profiling long-running
> > programs. Based on lsprof, contributed by Brett Rosen and Ted Czotter.
>
> >       New in version 2.5.
>
> Thanks John; I did read the manual which is why I decided to use cProfile
> as it was "recommended for most users".  I missed the last bit about "New
> in version 2.5."

Looks like our definitions of "read" differ :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: cProfile.py not found.

2009-04-04 Thread Rahul
John Yeung  wrote in news:c0752f32-b0cf-4fde-
87a8-eb665252e...@k41g2000yqh.googlegroups.com:

> I believe cProfile was added in 2.5.  Your best bet on 2.4 is probably
> the profile module.  That is what the docs recommend.
> 

Thanks John. That works. I'll use "profile" instead.

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


Re: cProfile.py not found.

2009-04-04 Thread John Machin
On Apr 5, 8:46 am, Rahul  wrote:
> I need to profile a slow-running code. The problem is I cannot seem to find  
> cProfile.py.
>
> Where can I get it? Is it not included in the normal distro? I tried
> googling it up and theres tons of info on how to use it but no links for
> where to download it from.
>
> I am using Python 2.4.4 (#3, Feb 17 2008, 15:06:10).

Read the fantastic manual:

http://docs.python.org/library/profile.html

Note: this is the *first* hit when you google either "cprofile" or
"cProfile.py".

"""
The Python standard library provides three different profilers:

   1.

  cProfile is recommended for most users; it’s a C extension with
reasonable overhead that makes it suitable for profiling long-running
programs. Based on lsprof, contributed by Brett Rosen and Ted Czotter.

  New in version 2.5.
"""
--
http://mail.python.org/mailman/listinfo/python-list


Re: cProfile.py not found.

2009-04-04 Thread Robert Kern

On 2009-04-04 18:08, John Yeung wrote:

I believe cProfile was added in 2.5.  Your best bet on 2.4 is probably
the profile module.  That is what the docs recommend.


Oops, I missed that piece of information. Alternately, the OP can install 
lsprof, which was cProfile's third-party incarnation before it got integrated 
into the stdlib:


  http://codespeak.net/svn/user/arigo/hack/misc/lsprof/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


[RELEASED] Python 3.1 alpha 2

2009-04-04 Thread Benjamin Peterson
On behalf of the Python development team, I'm thrilled to announce the second
alpha release of Python 3.1.

Python 3.1 focuses on the stabilization and optimization of features and changes
Python 3.0 introduced.  For example, the new I/O system has been rewritten in C
for speed.  Other features include an ordered dictionary implementation and
support for ttk Tile in Tkinter.  For a more extensive list of changes in 3.1,
see http://doc.python.org/dev/py3k/whatsnew/3.1.html or Misc/NEWS in the Python
distribution.

Please note that this is an alpha releases, and as such is not suitable for
production environments.  We continue to strive for a high degree of quality,
but there are still some known problems and the feature sets have not been
finalized.  This alpha is being released to solicit feedback and hopefully
discover bugs, as well as allowing you to determine how changes in 3.1 might
impact you.  If you find things broken or incorrect, please submit a bug report
at

 http://bugs.python.org

For more information and downloadable distributions, see the Python 3.1 website:

 http://www.python.org/download/releases/3.1/

See PEP 375 for release schedule details:

 http://www.python.org/dev/peps/pep-0375/


Regards,
-- Benjamin

Benjamin Peterson
benjamin at python.org
Release Manager
(on behalf of the entire python-dev team and 3.1's contributors)
--
http://mail.python.org/mailman/listinfo/python-list


Re: cProfile.py not found.

2009-04-04 Thread Rahul
Robert Kern  wrote in
news:mailman.3312.1238885852.11746.python-l...@python.org: 

> What system are you on? Some Linux distributions put it into a
> separate package, like python-profile. The python.org Windows and Mac
> binaries should have it, though. 
> 
> 

THanks Robert. I'm on RHEL. 

Tried yum search python-profile. No hits. Also tried a locate on 
cProfile. No hits again.

Did a yum search python. Huge list but nothing promising. Yet, I 
reproduce it below just in case its hidden somewhere in the list. What 
options do I have now? 

python-sqlite2.i386 : DB-API 2.0 interface for SQLite 3.x
tix.i386 : A set of extension widgets for Tk
tix-devel.i386 : Tk Interface eXtension development files
tix-doc.i386 : Tk Interface eXtension documentation
vim-enhanced.i386 : A version of the VIM editor which includes recent
  : enhancements.
Django.noarch : A high-level Python Web framework
Django-doc.noarch : Documentation for Django
MySQL-python.i386 : An interface to MySQL
OpenIPMI-python.i386 : OpenIPMI Python language bindings
PyQt.i386 : Python bindings for Qt
PyQt-examples.i386 : Examples for PyQt
PyXML.i386 : XML libraries for python.
PyYAML.noarch : YAML parser and emitter for Python
Pyrex.noarch : A compiler/language for writing Python extension modules.
PythonCard.noarch : PythonCard GUI construction toolkit
R2spec.noarch : Python script to generate R spec file
SOAPpy.noarch : Full-featured SOAP library for Python
TurboGears.noarch : Back-to-front web development in Python
ant-scripts.i386 : Additional scripts for ant
archivemail.noarch : A tool for archiving and compressing old email in 
mailboxes
audit-libs-python.i386 : Python bindings for libaudit
babel.noarch : Tools for internationalizing Python applications
beecrypt-python.i386 : Files needed for python applications using 
beecrypt.
booty.noarch : simple python bootloader config lib
bsf.i386 : Bean Scripting Framework
cobbler.noarch : Boot server configurator
ctopy.noarch : C to Python translator
cvs2svn.noarch : CVS to Subversion Repository Converter
db4.i386 : The Berkeley DB database library (version 4) for C.
dbus-python.i386 : D-Bus Python Bindings
ddd.i386 : GUI for several command-line debuggers
deluge.i386 : Graphical BitTorrent client with support for DHT, UPnP, and 
PEX
denyhosts.noarch : A script to help thwart ssh server attacks
epydoc.noarch : Edward Loper's Python API documentation generation tool
exaile.i386 : A music player
flumotion.i386 : Flumotion - the Fluendo Streaming Server
fuzzyclock.noarch : Generates fuzzy clock output
gamin-python.i386 : Python bindings for the gamin library
gdal.i386 : Geospatial Data Abstraction Library
gdal-python.i386 : Python modules for the GDAL file format library
getmail.noarch : POP3 mail retriever with reliable Maildir delivery
glade2.i386 : A GTK+ GUI builder.
gnome-menus.i386 : A menu system for the GNOME project
gnome-python2.i386 : The sources for the PyGNOME Python extension module
gnome-python2-applet.i386 : Python bindings for GNOME Panel applets.
gnome-python2-bonobo.i386 : Python bindings for interacting with bonobo.
gnome-python2-canvas.i386 : Python bindings for the GNOME Canvas.
gnome-python2-desktop.i386 : The sources for additional PyGNOME Python 
extension
   : modules for the GNOME desktop
gnome-python2-extras.i386 : The sources for additional. PyGNOME Python 
extension
  : modules.
gnome-python2-gconf.i386 : Python bindings for interacting with GConf
gnome-python2-gnomedesktop.i386 : Python bindings for interacting with 
gnome-
: desktop
gnome-python2-gnomekeyring.i386 : Python bindings for interacting with 
gnome-
: keyring
gnome-python2-gnomeprint.i386 : Python bindings for interacting with
  : libgnomeprint
gnome-python2-gnomevfs.i386 : Python bindings for interacting with gnome-
vfs
gnome-python2-gtkhtml2.i386 : Python bindings for interacting with 
gtkhtml2

python-twisted-names.i386 : A Twisted DNS implementation
python-twisted-web.i386 : Twisted web server, programmable in Python
python-twisted-web2.i386 : Twisted web server, programmable in Python
python-twisted-words.i386 : Twisted Words contains Instant Messaging 
implementations
python-twitter.noarch : A python wrapper around the Twitter API
python-tz.noarch : World Timezone Definitions for Python
python-urlgrabber.noarch : High-level cross-protocol url-grabber
python-urljr.noarch : Common interface to urllib2 and curl for making 
HTTP requests
python-urwid.noarch : Console UI Library for Python
python-urwid.i386 : Console UI Library for Python
python-utmp.i386 : Python module for working with utmp
python-vcpx.noarch : Version Control Patch eXchanger
python-virtinst.noarch : Python modules for starting Xen guest 
installations
python-vorbis.i386 : Python bindings for libvorbis
python-webob.noarch : WSGI request and response object
python-which.noarch : Small w

Re: cProfile.py not found.

2009-04-04 Thread John Yeung
I believe cProfile was added in 2.5.  Your best bet on 2.4 is probably
the profile module.  That is what the docs recommend.

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


Re: cProfile.py not found.

2009-04-04 Thread Robert Kern

On 2009-04-04 17:46, Rahul wrote:

I need to profile a slow-running code. The problem is I cannot seem to find
cProfile.py.

Where can I get it? Is it not included in the normal distro? I tried
googling it up and theres tons of info on how to use it but no links for
where to download it from.

I am using Python 2.4.4 (#3, Feb 17 2008, 15:06:10).

I am aware this is kind of dated but some of our legacy codes insist on
using that exact version.


What system are you on? Some Linux distributions put it into a separate package, 
like python-profile. The python.org Windows and Mac binaries should have it, though.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Creating a session in windows to auth to remote machines

2009-04-04 Thread ericwoodworth
On Apr 4, 6:39 pm, ericwoodwo...@gmail.com wrote:
> Hi,
>      I'm trying to auth to remote machines so I can plunder WMI to get
> logs and settings and the like.  My script works for most of my
> machines because they're all in the same domain and I run the script
> as somebody who has enough access to get at this stuff but for
> machines off the domain I'm stuck.
>
>      Now I'm primarily a sys/network admin and not a programmer.  As a
> sys admin if I had this problem while trying to pull eventlogs
> manually with eventvwr I would simply map a drive to the remote
> machine.  That would allow me to enter a username/password and then
> once I was authed I'd have a session and I'd be able to piggyback on
> that session to pull logs.
>
>      I'm looking to do exactly that from inside my script.  I could
> probably import os and call the net use command to map a drive and get
> a session that way but that feels really sloppy to me.  I want to be
> able to explicitly close this session when I'm done with it too.
>
>      So I figure there's a com object I could call to open this
> session for me but I can't figure out what it is.  Any help would be
> appreciated!
>
> Thanks

Also I am writing this in Python.  So I can use win32com if that's the
way to go or I can use anything python 2.6 has built in.  I mentioned
com objects because I'm using a lot of those currently but if there's
a more pythonic way to do what I"m after then I'm all ears.

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


cProfile.py not found.

2009-04-04 Thread Rahul
I need to profile a slow-running code. The problem is I cannot seem to find  
cProfile.py. 

Where can I get it? Is it not included in the normal distro? I tried 
googling it up and theres tons of info on how to use it but no links for 
where to download it from.

I am using Python 2.4.4 (#3, Feb 17 2008, 15:06:10). 

I am aware this is kind of dated but some of our legacy codes insist on 
using that exact version. 


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


Creating a session in windows to auth to remote machines

2009-04-04 Thread ericwoodworth
Hi,
 I'm trying to auth to remote machines so I can plunder WMI to get
logs and settings and the like.  My script works for most of my
machines because they're all in the same domain and I run the script
as somebody who has enough access to get at this stuff but for
machines off the domain I'm stuck.

 Now I'm primarily a sys/network admin and not a programmer.  As a
sys admin if I had this problem while trying to pull eventlogs
manually with eventvwr I would simply map a drive to the remote
machine.  That would allow me to enter a username/password and then
once I was authed I'd have a session and I'd be able to piggyback on
that session to pull logs.

 I'm looking to do exactly that from inside my script.  I could
probably import os and call the net use command to map a drive and get
a session that way but that feels really sloppy to me.  I want to be
able to explicitly close this session when I'm done with it too.

 So I figure there's a com object I could call to open this
session for me but I can't figure out what it is.  Any help would be
appreciated!

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Gabriel Genellina

En Sat, 04 Apr 2009 14:11:12 -0300, gert  escribió:


On Apr 4, 5:20 pm, Kushal Kumaran  wrote:

On Fri, 03 Apr 2009 22:10:36 +0200
Christian Heimes  wrote:
> gert wrote:



> > I do understand, and I went looking into pySerial, but it is a long
> > way from getting compatible with python3.x and involves other libs
> > that are big and non pyhton3.x compatible.

> So don't use Python 3.0. Most people are still using Python 2.5 or
> 2.6.

Alternatively, you could look into the pySerial source and find out
what it does.


I think pywin32 is the way they do the things I want. Witch is not
python3 ready and way to much work around to do it clean. Using ctypes
is a option but you have to really know what you are doing and what
you are looking for.


The last pywin32 release (213) does work with Python 3.
If you can wait a few days, I'm working on a proper port of pyserial.  
Preliminary testing shows it's working fine on Windows. Basically, I've  
modified the read/write methods to use bytes instead of str, and 2to3 did  
the rest:


Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit  
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
p3> import serial
p3> ser = serial.Serial(2)
p3> ser.write(b"ATI7\r\n")
p3> for line in ser: print(line.rstrip().decode("ascii","replace"))
...
ATI7

Configuration Profile...

Product type   US/Canada Internal
OptionsV32bis,V.FC,V.34+
Fax OptionsClass 1/Class 2.0
Clock Freq 92.0Mhz
Line Options   Caller ID,Distinctive Ring
Voice Options  Speakerphone,TAD
Eprom  256k
Ram64k

EPROM date 5/13/96
DSP date   5/13/96

EPROM rev  2.0
DSP rev2.0

OK
^C

--
Gabriel Genellina

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


Re: is there a way to collect twitts with python?

2009-04-04 Thread '2+
nice info, thanx
that
# stalk my stalkers
example look smart
i won't use that one if it was for this ml ;D

On Sun, Apr 5, 2009 at 1:22 AM, Bradley Wright  wrote:
> Just to pimp my own wares:
>
> http://github.com/bradleywright/yatcip/tree/master
>
> A Python Twitter client.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

-- 
SaRiGaMa's Oil Vending Orchestra
is podcasting:
http://sarigama.namaste.jp/podcast/rss.xml
and supplying oil.py for free:
http://oilpy.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: with open('com1', 'r') as f:

2009-04-04 Thread Christian Heimes
gert wrote:
> On Apr 3, 10:10 pm, Christian Heimes  wrote:
>> gert wrote:
>>> I do understand, and I went looking into pySerial, but it is a long
>>> way from getting compatible with python3.x and involves other libs
>>> that are big and non pyhton3.x compatible.
>> So don't use Python 3.0. Most people are still using Python 2.5 or 2.6.
> 
> With all respect but why do people in general avoid the question when
> they do not know something?
> I appreciate the answer and its a valid solution, never the less
> useless in the answer I seek.

You are missing some background information. :)
I've spent a considerable amount of time with the design and development
of Python 3.0. I don't mention the fact in order to show off. I just
wanna explain to you that my suggestion has a solid background.

You are going throw a lot of unnecessary pain and suffering. Python 3.0
is for people, who like to play with cutting edge software and for
library developers, that port their code to 3.0. I appreciate your hard
work but it's really the wrong way. If you like to offer your help then
help the developers of pyserial. Please don't try to come by with a
hacky approach as using the old MS DOS magic files.

Christian

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


Re: python needs leaning stuff from other language

2009-04-04 Thread Robert Kern

On 2009-04-04 12:07, Tim Wintle wrote:

On Sat, 2009-04-04 at 02:03 -0500, Robert Kern wrote:

Let's be clear: python-ideas seems positive on the idea of adding a .clear()
method. *Completely removing* slice assignment has not been broached there.


Yup, sorry - I did mean to refer to the initial suggestion, rather than
my comments


(I didn't expect such strong responses btw!)

You are proposing the removal of a general, orthogonal feature (and breaking
code in consequence!) just because of a new syntax for a single special case of
that feature. That is quite simply ridiculous.


Ok, I may have come across a little strongly (was very tired) - I'm not
_actually_ saying we should remove it, I'm just pointing out why
adding .clear() to lists seems to be unnecessary and slightly messy. The
suggested removal of assignments to slices is a theoretical statement.


But can you see why your wording might lead the rest of us to believe otherwise? 
 :-)



.clear() would be non-orthogonal syntactic sugar. That's okay! Python has
syntactic sugar in a number of other places, too! Appropriate doses of syntactic
sugar and non-orthogonality are precisely what lets you implement "There should
be one-- and preferably only one --obvious way to do it." The really key word in
that sentence is "obvious", not "one".

FWIW, removing slice assignment would be a gross form of non-orthogonality, too.
__getitem__, __setitem__ and __delitem__ should all be able to accept the same
indices (or else raise exceptions in the case of immutability).


hummm - I'm sure it would be confusing behaviour if it was not
available, but I'm not sure how it would be non-orthogonal


I might be abusing the term, but to me, orthogonality doesn't just mean avoiding 
overlapping functionality. It also means not putting in special-case limitations 
for otherwise general features. It would be odd if you could use integer indices 
for __getitem__, __setitem__ and __delitem__, but slice indices would work for 
__getitem__ and not the others.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Diez B. Roggisch

gert schrieb:

On Apr 3, 10:10 pm, Christian Heimes  wrote:

gert wrote:

I do understand, and I went looking into pySerial, but it is a long
way from getting compatible with python3.x and involves other libs
that are big and non pyhton3.x compatible.

So don't use Python 3.0. Most people are still using Python 2.5 or 2.6.


With all respect but why do people in general avoid the question when
they do not know something?
I appreciate the answer and its a valid solution, never the less
useless in the answer I seek.

I hope I did not offend anybody. When you want to do something about
the future, you have to take the hard way, so others can take the easy
way. If somebody is stuck going the hard way, to clear it for others,
you can not expect them to be satisfied with a easy answer.


But your path is clearly *not* the future. It would be fixing win32 and 
pyserial, if anything.


And the suggestion to change the set of tools if there is no reason to 
stick to the ones you use now certainly is a valid answer. Especially if 
they do know that these solutions work.


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


Re: Testing dynamic languages

2009-04-04 Thread bearophileHUGS
grkunt...:
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.

Others have already given you most of the answers (summary: don't do
that. Don't fight the language. Use doctests). My other suggestion is
to read code coming from 5+ Python programs written by other
(different) people. You will see how to use Python.

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


RE: Generators/iterators, Pythonicity, and primes

2009-04-04 Thread John Posner
Mark Tolonen said:

 >> p <= sqrt(n) works a little better :^)
 >> 
 >> -Mark
 >> 

Right you are -- I found that bug in my last-minute check, and then I forgot
to trannscribe the fix into the email message. Duh -- thanks!

-John 






E-mail message checked by Spyware Doctor (6.0.0.386)
Database version: 5.12110
http://www.pctools.com/en/spyware-doctor-antivirus/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best Compatible JS Lib for Django

2009-04-04 Thread Daniel Fetchinson
> Does anyone have experience with using JS Libraries with Django?
> Do some work better than others and are easier to code with?

You might want to ask this on the django list.

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: python needs leaning stuff from other language

2009-04-04 Thread Diez B. Roggisch

Tim Wintle schrieb:

On Sat, 2009-04-04 at 02:03 -0500, Robert Kern wrote:
Let's be clear: python-ideas seems positive on the idea of adding a .clear() 
method. *Completely removing* slice assignment has not been broached there.


Yup, sorry - I did mean to refer to the initial suggestion, rather than
my comments


(I didn't expect such strong responses btw!)
You are proposing the removal of a general, orthogonal feature (and breaking 
code in consequence!) just because of a new syntax for a single special case of 
that feature. That is quite simply ridiculous.


Ok, I may have come across a little strongly (was very tired) - I'm not
_actually_ saying we should remove it, I'm just pointing out why
adding .clear() to lists seems to be unnecessary and slightly messy. The
suggested removal of assignments to slices is a theoretical statement.

.clear() would be non-orthogonal syntactic sugar. That's okay! Python has 
syntactic sugar in a number of other places, too! Appropriate doses of syntactic 
sugar and non-orthogonality are precisely what lets you implement "There should 
be one-- and preferably only one --obvious way to do it." The really key word in 
that sentence is "obvious", not "one".


FWIW, removing slice assignment would be a gross form of non-orthogonality, too. 
__getitem__, __setitem__ and __delitem__ should all be able to accept the same 
indices (or else raise exceptions in the case of immutability).


hummm - I'm sure it would be confusing behaviour if it was not
available, but I'm not sure how it would be non-orthogonal


>>> l = range(10)
>>> l[3:7] = range(4)
>>> l
[0, 1, 2, 0, 1, 2, 3, 7, 8, 9]

How do you want to do that with clear?

That l[:] = [] clears a list is more of an "accident" than the intent of 
slice-assignment. Removing it in favor of clear() would remove an 
orthogonal feature of updating parts of a list with another iterable.


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


Re: Generators/iterators, Pythonicity, and primes

2009-04-04 Thread Mark Tolonen


"John Posner"  wrote in message 
news:af9fbcc3a7624599a6f51bad2397e...@amdup...

Inspired by recent threads (and recalling my first message to Python
edu-sig), I did some Internet searching on producing prime numbers using
Python generators. Most algorithms I found don't go for the infinite,
contenting themselves with "list all the primes below a given number".

Here's a very Pythonic (IMHO) implementation that keeps going and going 
and

going ...:

from itertools import count
from math import sqrt

def prime_gen():
   """
   Generate all prime numbers
   """
   primes = []
   for n in count(2):
   if all(n%p for p in primes if p < sqrt(n)):
   primes.append(n)
   yield n


p <= sqrt(n) works a little better :^)

-Mark


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


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread John Doe
Dave Angel  wrote:
> John Doe wrote:

>> ...at least by the time I move from Windows XP to Windows 7,
>> very likely I will be using a different file manager. If I cannot
>> search Python files, now might be a good time to switch.

> and the product xplorer2 is athttp://zabkat.com/
> Std version is $30, but there's a free version also.

The free version uses Windows Explorer search, therefore it will not
find text in *.py files. Same with Ultra Explorer.

Another file manager, FreeCommander, does find text in Python files.
--
http://mail.python.org/mailman/listinfo/python-list


Can't one collect twitts and twits in any language?

2009-04-04 Thread Casey Hawthorne
:)
--
Regards,
Casey
--
http://mail.python.org/mailman/listinfo/python-list


Re: lxml and xslt extensions

2009-04-04 Thread Stefan Behnel
Hi,

dasacc22 wrote:
> On Apr 4, 11:31 am, dasacc22 wrote:
>> Im not sure where else to ask this.

The best place to ask is the lxml mailing list:

http://codespeak.net/mailman/listinfo/lxml-dev


>> But basically Im having trouble
>> figuring out how to successfully apply multiple extensions in a single
>> transformation. So for example if i have
>> 
>> 
>> 
>> 
>> 
>> 
>>
>> in my xsl and my xslt extension looks like
>>
>> class TagExtension(etree.XSLTExtension):
>>   def execute( ..., output_parent):
>> print 'executing tag_extension'
>> tag = etree.Element('p')
>> tag.text = 'Hello'
>> output_parent.append(tag)
>>
>> well then the transformation works for the first tag and appends it to
>> the root of the created doc but all subsequent calls dont append
>> (maybe b/c output_parent is now somewhere else for return?). And to
>> clarify, I know that its the first call that completes and all
>> subsequent calls fail b/c i have a subsequent call that performs a
>> different transformation.
> 
> Oh well I found the culprit, etree.tostring seems to cut it off after
> the first transformation,

Not sure what you mean here. Could you post your question on the lxml
mailing list and add a runnable example that shows the behaviour?


> simply doing a
> 
> $> print result
> 
> displays the entire document. To make use of the keyword options
> xml_declaration, pretty_print, encoding, I tried using the .write
> method of result to a StringIO but it produces the same clipped
> result. Guess Ill have to edit the .docinfo attributes on the result
> and return the string

.docinfo is basically read-only. The result of the XSLT is serialised as
requested by the xsl:output element in the stylesheet.

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


Generators/iterators, Pythonicity, and primes

2009-04-04 Thread John Posner
Inspired by recent threads (and recalling my first message to Python
edu-sig), I did some Internet searching on producing prime numbers using
Python generators. Most algorithms I found don't go for the infinite,
contenting themselves with "list all the primes below a given number".

Here's a very Pythonic (IMHO) implementation that keeps going and going and
going ...:

from itertools import count
from math import sqrt

def prime_gen():
"""
Generate all prime numbers
"""
primes = []
for n in count(2):
if all(n%p for p in primes if p < sqrt(n)):
primes.append(n)
yield n

The use of all() is particularly nifty (see
http://code.activestate.com/recipes/576640/). And so is the way in which the
list comprehension easily incorporates the sqrt(n) optimization.

Question: Is there a way to implement this algorithm using generator
expressions only -- no "yield" statements allowed?

BTW -- thank you, John Machin, for the spanking ('I'd worry about "correct"
before "Pythonic"') in a previous message. I *did* manage to post a
correction to the needless conversion of a string to a list:

   b in list("\r\n\t")

... a few hours before your message arrived (Wed Apr 1 19:44:01 CEST 2009)!





E-mail message checked by Spyware Doctor (6.0.0.386)
Database version: 5.12110
http://www.pctools.com/en/spyware-doctor-antivirus/
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict view to list

2009-04-04 Thread Aahz
In article <6b4065b0-6af7-4aff-8023-40e5d521f...@v19g2000yqn.googlegroups.com>,
Luis Gonzalez   wrote:
>
>Yes, I know the python approach is to use built-ins.
>But wouldn't it be cool if we could do mydict.values().tolist()
>instead?
>It would be more regular and intuitive and readable from an OO point
>of view.
>In my oppinion, this would be cleaner.
>Built-ins used like this look like an early decission made when
>designing an imperative language.

What kind of language do you think Python is?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
--
http://mail.python.org/mailman/listinfo/python-list


Best Compatible JS Lib for Django

2009-04-04 Thread ntwrkd
Does anyone have experience with using JS Libraries with Django?
Do some work better than others and are easier to code with?

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Gabriel Genellina

En Sat, 04 Apr 2009 11:29:22 -0300, gert  escribió:


On Apr 4, 12:58 am, Lawrence D'Oliveiro  wrote:

In message <8bc55c05-19da-41c4-

b916-48e0a4be4...@p11g2000yqe.googlegroups.com>, gert wrote:
>     with open('com1', 'r') as f:
>         for line in f:
>              print('line')

Why bother, why not just

    for line in open('com1', 'r') :
        print line


Interesting :)
So its does the same thing as with right ?
Automatic closing and finalizing stuff.


No, it does not. Either use `with` o a `try...finally` block.

--
Gabriel Genellina

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


Re: Hash of None varies per-machine

2009-04-04 Thread Peter Pearson
On 03 Apr 2009 10:57:05 -0700, Paul Rubin  wrote:
> ben.tay...@email.com writes:
>> 1. Is it correct that if you hash two things that are not equal they
>> might give you the same hash value?
>
> Yes, hashes are 32 bit numbers and there are far more than 2**32
> possible Python values (think of long ints), so obviously there must
> be multiple values that hash to the same slot.

For example, on this machine:

Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

 hash( "latox" ) == hash( "uzyky" )
True

YMMV.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: django model problem

2009-04-04 Thread Mark
> 
> Anyway, since I don't have time to actually install and configure Django 
> to experiment, I'd suggest you post a query on the django-users mailing 
> list, at http://groups.google.com/group/django-users
 
Yes, that's what I did - it seems my problem is either a tough one, or it's
just impossible to do what I want. 
Anyway great thanks for your interest and help!

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


Re: Testing dynamic languages

2009-04-04 Thread grkuntzmd
This may be obvious but, clearly there are (at least) two general
types of errors: those caused by data external to the program and
those caused by bugs in the program. For all inputs coming into the
program from outside, such as user inputs and data coming over a
network, the inputs must be completely checked -- always assume that
they will be incorrect and are intended to crash your code -- be
pleasantly surprised when they are not :-). Check for all bad inputs.

If the data are from inside the program, the assumption may be that
they are good and if not, it was a bug. I suppose you can write unit
tests on each routine to see that the methods that routine calls are
with valid arguments (using mocks). I actually tried this in a Java
program using JMockit; it was tedious, but it did catch a few
"potential" bugs. I would love to say that I ALWAYS remember the input
and output condition of every subroutine I write, but I just finished
a new feature for a company project that involved 100+ routines and
classes and I admit that I don't always remember which ones can return
null and which always return empty arrays, for example, even though I
try to write JavaDocs at the top of each routine. By mocking these
routines, I can check that the caller always handles each case
gracefully.
--
http://mail.python.org/mailman/listinfo/python-list


Re: with open('com1', 'r') as f:

2009-04-04 Thread gert
On Apr 4, 5:20 pm, Kushal Kumaran  wrote:
> On Fri, 03 Apr 2009 22:10:36 +0200
>
> Christian Heimes  wrote:
> > gert wrote:
> > > I do understand, and I went looking into pySerial, but it is a long
> > > way from getting compatible with python3.x and involves other libs
> > > that are big and non pyhton3.x compatible.
>
> > So don't use Python 3.0. Most people are still using Python 2.5 or
> > 2.6.
>
> Alternatively, you could look into the pySerial source and find out
> what it does.

I think pywin32 is the way they do the things I want. Witch is not
python3 ready and way to much work around to do it clean. Using ctypes
is a option but you have to really know what you are doing and what
you are looking for.

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


Re: python needs leaning stuff from other language

2009-04-04 Thread Tim Wintle
On Sat, 2009-04-04 at 02:03 -0500, Robert Kern wrote:
> 
> Let's be clear: python-ideas seems positive on the idea of adding a .clear() 
> method. *Completely removing* slice assignment has not been broached there.

Yup, sorry - I did mean to refer to the initial suggestion, rather than
my comments

> 
> > (I didn't expect such strong responses btw!)
> 
> You are proposing the removal of a general, orthogonal feature (and breaking 
> code in consequence!) just because of a new syntax for a single special case 
> of 
> that feature. That is quite simply ridiculous.

Ok, I may have come across a little strongly (was very tired) - I'm not
_actually_ saying we should remove it, I'm just pointing out why
adding .clear() to lists seems to be unnecessary and slightly messy. The
suggested removal of assignments to slices is a theoretical statement.

> 
> .clear() would be non-orthogonal syntactic sugar. That's okay! Python has 
> syntactic sugar in a number of other places, too! Appropriate doses of 
> syntactic 
> sugar and non-orthogonality are precisely what lets you implement "There 
> should 
> be one-- and preferably only one --obvious way to do it." The really key word 
> in 
> that sentence is "obvious", not "one".
> 
> FWIW, removing slice assignment would be a gross form of non-orthogonality, 
> too. 
> __getitem__, __setitem__ and __delitem__ should all be able to accept the 
> same 
> indices (or else raise exceptions in the case of immutability).

hummm - I'm sure it would be confusing behaviour if it was not
available, but I'm not sure how it would be non-orthogonal

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


Re: Testing dynamic languages

2009-04-04 Thread Tim Wintle
On Sat, 2009-04-04 at 06:37 -0700, grkunt...@gmail.com wrote:
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.

At some point you should wrap it in a try/except block - but only at the
point where you want the exception to be handled. That will normally be
quite far up, and you'll just let the exception travel back up to that
point.


for example, in a web server type of thing you might have something
vaguely like


def main:
  for request in request_itter:
try:
  headers = request.get_headers()
  dispatch = get_dispatch_fn(headers)
  response = dispatch(response)
except:
  send_500()

You probably then don't need to catch any exceptions in the get_headers,
or actual processing methods (unless you are writing to sql or
something, when you might want to wrap all statements in a try block,
and then put a "ROLLBACK;" query in the except block (and then raise the
caught exception so it goes back the the block above)

> 
> Is this the experience that Python programmer (of large projects) see?
> Do you also write unit tests to confirm that the methods actually
> check for and catch "bad" parameter types? If I am writing small one-
> off scripts, I wouldn't worry about it, but if I am writing a large
> system that must have 99+% uptime without constant monitoring, this
> really should be verified.

I write large applications with a target of 99.9% uptime, and I don't
find it a problem. occasionally I have to check parameters, but that's
not very often

> 
> Up for discussion...
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Testing dynamic languages

2009-04-04 Thread Francesco Bochicchio
On Sat, 04 Apr 2009 07:37:44 -0700, grkuntzmd wrote:

> I am a Java developer. There, I said it :-).
> 
> When I am writing code, I can  rely on the compiler to confirm that
> any methods I write will be called with parameters of the "right"
> type. I do not need to test that parameter #1 really is a String
> before I call some method on it that only works on Strings.
> 
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.
> 
> Is this the experience that Python programmer (of large projects) see?
> Do you also write unit tests to confirm that the methods actually
> check for and catch "bad" parameter types? If I am writing small one-
> off scripts, I wouldn't worry about it, but if I am writing a large
> system that must have 99+% uptime without constant monitoring, this
> really should be verified.
> 
> Up for discussion...

Uhm. 
I write large bodies of code for living ... not in Python, unfortunately.
I usually divide my code in two classes wrt sanity checks : inner code and
boundary code. Boundary code gets paranoic checks on everything:
arguments, consistency etc ... also with static typing : an 'int'
parameter declaration in C/C++ make sure that your function gets an
integer, but ensure nothing in the way of minimum and maximum value, so
before using it - say - as an array index, it is better to check
that. Inner code gets less checks, based on the assumptions that inputs
have been properly checked by the boundary functions.

This method is not without risks - an architectural change can move a 
function from an inner zone to a boundary zone, and I may forget to
'fortify' the function. However, this is a guideline that served me well.

Beside that there is another guideline I apply to languages like java and
python - programs in these languages do not 'crash' ... they throw
exceptions. Now, supposing to add an input check  : what are you
going to do if you find bad data? In the answer is - as often the case -
throw an exception, then maybe the check is not worth much ...

There are exceptions to this guideline, as always, like if you want to
generate a more meaningful exception, but this is another guideline I
tend to follow. And this means that my level of checking in python is 
much lower than in - say - C++. And I don't worry too much about argument
types, more about external inputs with the right 'semantic'.

The one coding behaviour that dynamic types forced me to change, is that
now I tend to build programs more incrementally, because catching typos
error and logic errors at the same time on a large body of code can be
frustrating and not very productive ... but I find myself to use now the
same approach also when I code in statically typed languages : a bit
slower at beginning, but tend to procuce more reliable results .

Ciao

FB


 
 
 

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


Re: is there a way to collect twitts with python?

2009-04-04 Thread Bradley Wright
Just to pimp my own wares:

http://github.com/bradleywright/yatcip/tree/master

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


Re: Hash of None varies per-machine

2009-04-04 Thread Hendrik van Rooyen
"Steven D'Aprano"  wrote:


>Seems to me you have misunderstood the way pickling works.

Yeah right - have you ever looked at the pickle code?

Good to hear it "just works"

:-)

- Hendrik

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


Re: lxml and xslt extensions

2009-04-04 Thread dasacc22
On Apr 4, 11:31 am, dasacc22  wrote:
> Hi,
>
> Im not sure where else to ask this. But basically Im having trouble
> figuring out how to successfully apply multiple extensions in a single
> transformation. So for example if i have
> 
> 
> 
> 
> 
> 
>
> in my xsl and my xslt extension looks like
>
> class TagExtension(etree.XSLTExtension):
>   def execute( ..., output_parent):
>     print 'executing tag_extension'
>     tag = etree.Element('p')
>     tag.text = 'Hello'
>     output_parent.append(tag)
>
> well then the transformation works for the first tag and appends it to
> the root of the created doc but all subsequent calls dont append
> (maybe b/c output_parent is now somewhere else for return?). And to
> clarify, I know that its the first call that completes and all
> subsequent calls fail b/c i have a subsequent call that performs a
> different transformation.
>
> Thanks for any help or hints,
> Daniel

Oh well I found the culprit, etree.tostring seems to cut it off after
the first transformation, simply doing a

$> print result

displays the entire document. To make use of the keyword options
xml_declaration, pretty_print, encoding, I tried using the .write
method of result to a StringIO but it produces the same clipped
result. Guess Ill have to edit the .docinfo attributes on the result
and return the string
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread Dave Angel

John Doe wrote:

Tim Golden  wrote:
 
Now I think about it, try searching for "xplorer2" since I think I 
mentioned that I have used that instead of explorer for some while. 


Yeah... at least by the time I move from Windows XP to Windows 7, very 
likely I will be using a different file manager. If I cannot

search Python files, now might be a good time to switch. Thanks for
the search criteria, I will look for that thread.
  
The original thread is at
http://mail.python.org/pipermail/tutor/2009-January/066765.html


and the product xplorer2 is athttp://zabkat.com/
Std version is $30, but there's a free version also.

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


Re: Why doesn't StopIteration get caught in the following code?

2009-04-04 Thread andrew cooke
grocery_stocker wrote:
 while True:
> ...i = gen.next()
> ...print i
> ...
> 0
> 1
> 4

python's magic isn't as magic as you hope.

roughly speaking, it only does the necessary rewriting (writing the
equivalent code with next etc etc) when you define a function or a method
that contains "yield".  the above doesn't, so it's not rewritten and
there's no magic.

more exactly:
http://docs.python.org/reference/datamodel.html#index-1747

andrew


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


Re: Why doesn't StopIteration get caught in the following code?

2009-04-04 Thread Dave Angel

grocery_stocker wrote:

Given the following

[cdal...@localhost ~]$ python
Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
  

def counter():


...   mylist = range(3)
...   for i in mylist:
...  yield i*i
...
  

counter



  

gen = counter()
gen



  

while True:


...i = gen.next()
...print i
...
0
1
4
Traceback (most recent call last):
  File "", line 2, in ?
StopIteration


I thought the 'for' in counter() was supposed to catch StopIteration.
Ie, I thought that something like

...   for i in mylist:
...  yield i*i

Got translated to something like
  

try:


...while True:
...   do some stuff
... except StopIteration:
...pass
...


  
There are two separate StopIteration's here.  The for statement you 
describe will indeed catch the StopIteration from the list's iterator.


But that for statement is inside a generator function, and the generator 
function throws a StopIteration when it returns (as opposed to when it 
yields).  If you had used that generator inside another for statement, 
it would have worked as you expect.  But when you call nest() 
explicitly, you have to be prepared for the exception.  Clearly, the 
while True loop cannot go forever, when your generator is finite.



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


lxml and xslt extensions

2009-04-04 Thread dasacc22
Hi,

Im not sure where else to ask this. But basically Im having trouble
figuring out how to successfully apply multiple extensions in a single
transformation. So for example if i have







in my xsl and my xslt extension looks like

class TagExtension(etree.XSLTExtension):
  def execute( ..., output_parent):
print 'executing tag_extension'
tag = etree.Element('p')
tag.text = 'Hello'
output_parent.append(tag)

well then the transformation works for the first tag and appends it to
the root of the created doc but all subsequent calls dont append
(maybe b/c output_parent is now somewhere else for return?). And to
clarify, I know that its the first call that completes and all
subsequent calls fail b/c i have a subsequent call that performs a
different transformation.

Thanks for any help or hints,
Daniel
--
http://mail.python.org/mailman/listinfo/python-list


Why doesn't StopIteration get caught in the following code?

2009-04-04 Thread grocery_stocker
Given the following

[cdal...@localhost ~]$ python
Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def counter():
...   mylist = range(3)
...   for i in mylist:
...  yield i*i
...
>>> counter

>>> gen = counter()
>>> gen

>>> while True:
...i = gen.next()
...print i
...
0
1
4
Traceback (most recent call last):
  File "", line 2, in ?
StopIteration


I thought the 'for' in counter() was supposed to catch StopIteration.
Ie, I thought that something like

...   for i in mylist:
...  yield i*i

Got translated to something like
>>> try:
...while True:
...   do some stuff
... except StopIteration:
...pass
...

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Kushal Kumaran
On Fri, 03 Apr 2009 22:10:36 +0200
Christian Heimes  wrote:

> gert wrote:
> > I do understand, and I went looking into pySerial, but it is a long
> > way from getting compatible with python3.x and involves other libs
> > that are big and non pyhton3.x compatible.
> 
> So don't use Python 3.0. Most people are still using Python 2.5 or
> 2.6.
> 

Alternatively, you could look into the pySerial source and find out
what it does.

-- 
kushal

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


Re: statvfs clearance

2009-04-04 Thread Dave Angel



Hrvoje Niksic wrote:

Sreejith K  writes:

  

Python's statvfs module contains the following indexes to use with
os.statvfs() that contains the specified information

statvfs.F_BSIZE
Preferred file system block size.


[...]
  

statvfs.F_NAMEMAX
Maximum file name length.

Can anyone tell me (or give me some links to know) what are these
values ? The first three I know, I need to know about the rest



  

The following web page describes them:
   http://docs.python.org/library/statvfs.html
but you already knew that much.  So what are you really asking for?

You can simply print them, they are integers:

  

import statvfs
statvfs.F_FLAG


8

  
But those values may be specific to a particular python implementation.  
No reason to assume they'd be the same across OS platforms, or between 
versions 2.5 and 2.6.  The whole thing is deprecated, and is eliminated 
in 3.0


The term we used to use for these is "magic numbers."   Using 
magic-numbers directly in your code is a good way to ensure future time 
debugging.


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


Re: python needs leaning stuff from other language

2009-04-04 Thread Zamnedix
On Apr 3, 8:48 am, Steven D'Aprano  wrote:
> On Fri, 03 Apr 2009 08:23:22 -0700, Zamnedix wrote:
> > On Apr 2, 3:25 pm, online.serv...@ymail.com wrote:
> >> python's list needs a thing  list.clear()  like c# arraylist and
> >> python needs a writeline() method
>
> > Please don't post things like list before you do any research. You don't
> > know what you are talking about.
>
> The original poster may or may not know what he is talking about, but
> adding a clear() method to lists seems to be very much in demand. I'd
> vote Yes for one.
>
> Besides, this news group is for people to ask questions about Python,
> even stupid questions. It's not just for experts only.
>
> --
> Steven

Sorry. It was inappropriate. I just get a little mad at people who
don't even ATTEMPT to speak proper English. And then they go on
bashing our language without any sort of context.
--
http://mail.python.org/mailman/listinfo/python-list


Re: statvfs clearance

2009-04-04 Thread Albert Hopkins
On Sat, 2009-04-04 at 15:48 +0200, Hrvoje Niksic wrote:
> Sreejith K  writes:
> 
> > Python's statvfs module contains the following indexes to use with
> > os.statvfs() that contains the specified information
> >
> > statvfs.F_BSIZE
> > Preferred file system block size.
> [...]
> > statvfs.F_NAMEMAX
> > Maximum file name length.
> >
> > Can anyone tell me (or give me some links to know) what are these
> > values ? The first three I know, I need to know about the rest
> 
> You can simply print them, they are integers:
> 
> >>> import statvfs
> >>> statvfs.F_FLAG
> 8
> --

Oh, did the OP mean the values of the indices?  Yeah, of course you can
just print them.  Or even look at statvfs.py.  It's a whopping 15 lines:

"""Constants for interpreting the results of os.statvfs() and
os.fstatvfs().""" 

# Indices for statvfs struct members in the tuple returned by
# os.statvfs() and os.fstatvfs().

F_BSIZE   = 0   # Preferred file system block size
F_FRSIZE  = 1   # Fundamental file system block size
F_BLOCKS  = 2   # Total number of file system blocks (FRSIZE)
F_BFREE   = 3   # Total number of free blocks
F_BAVAIL  = 4   # Free blocks available to non-superuser
F_FILES   = 5   # Total number of file nodes
F_FFREE   = 6   # Total number of free file nodes
F_FAVAIL  = 7   # Free nodes available to non-superuser
F_FLAG= 8   # Flags (see your local statvfs man page)
F_NAMEMAX = 9   # Maximum file name length


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


Re: with open('com1', 'r') as f:

2009-04-04 Thread gert
On Apr 3, 10:10 pm, Christian Heimes  wrote:
> gert wrote:
> > I do understand, and I went looking into pySerial, but it is a long
> > way from getting compatible with python3.x and involves other libs
> > that are big and non pyhton3.x compatible.
>
> So don't use Python 3.0. Most people are still using Python 2.5 or 2.6.

With all respect but why do people in general avoid the question when
they do not know something?
I appreciate the answer and its a valid solution, never the less
useless in the answer I seek.

I hope I did not offend anybody. When you want to do something about
the future, you have to take the hard way, so others can take the easy
way. If somebody is stuck going the hard way, to clear it for others,
you can not expect them to be satisfied with a easy answer.

Sorry.

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


Re: python needs leaning stuff from other language

2009-04-04 Thread Paul McGuire
On Apr 3, 11:48 pm, Tim Wintle  wrote:
> del mylist[:]
> * or *
> mylist[:] = []
> * or *
> mylist = []
>
> which, although semantically similar are different as far as the
> interpreter are concerned (since two of them create a new list):
>

Only the last item creates a new list of any consequence.  The first
two retain the original list and delete or discard the items in it.  A
temporary list gets created in the 2nd option, and is then used to
assign new contents to mylist's [:] slice - so yes, technically, a new
list *is* created in the case of this option. But mylist does not get
bound to it as in the 3rd case.  In case 2, mylist's binding is
unchanged, and the temporary list gets GC'ed almost immediately.

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


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread drobi...@gmail.com
On Apr 4, 12:21 am, John Doe  wrote:
> Anybody have a solution for Windows (XP) Explorer search not finding
> ordinary text in *.py files?
>
> Thanks.

Googling turns up this.
http://www.pcmag.com/article2/0,4149,1206399,00.asp

I haven't tried it myself.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread Luis Gonzalez
On Apr 4, 11:17 am, Emmanuel Surleau 
wrote:
> On Saturday 04 April 2009 15:37:44 grkunt...@gmail.com wrote:
>
> > I am a Java developer. There, I said it :-).

Don't worry. I also do terrible things to support my family...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread andrew cooke
andrew cooke wrote:
> if you are going to do that, stay with java.  seriously - i too, am a java
> developer about half the time, and you can make java pretty dynamic if you
> try hard enough.  look at exploiting aspects and functional programming
> libraries, for example.

also, of course, scala.  andrew

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread gert
On Apr 4, 12:58 am, Lawrence D'Oliveiro  wrote:
> In message <8bc55c05-19da-41c4-
>
> b916-48e0a4be4...@p11g2000yqe.googlegroups.com>, gert wrote:
> >     with open('com1', 'r') as f:
> >         for line in f:
> >              print('line')
>
> Why bother, why not just
>
>     for line in open('com1', 'r') :
>         print line

Interesting :)
So its does the same thing as with right ?
Automatic closing and finalizing stuff.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to free /destroy object created by PyTuple_New

2009-04-04 Thread Andrew Svetlov
To destroy every python object you need to call Py_DECREF.
To call python code fron you C thread you need to use pair
PyGILState_Ensure/PyGILState_Release.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to extract from regex in if statement

2009-04-04 Thread Paul McGuire
On Apr 3, 9:26 pm, Paul Rubin  wrote:
> bwgoudey  writes:
> > elif re.match("^DATASET:\s*(.+) ", line):
> >         m=re.match("^DATASET:\s*(.+) ", line)
> >         print m.group(1))
>
> Sometimes I like to make a special class that saves the result:
>
>   class Reg(object):   # illustrative code, not tested
>      def match(self, pattern, line):
>         self.result = re.match(pattern, line)
>         return self.result
>
I took this a little further, *and* lightly tested it too.

Since this idiom makes repeated references to the input line, I added
that to the constructor of the matching class.

By using __call__, I made the created object callable, taking the RE
expression as its lone argument and returning a boolean indicating
match success or failure.  The result of the re.match call is saved in
self.matchresult.

By using __getattr__, the created object proxies for the results of
the re.match call.

I think the resulting code looks pretty close to the original C or
Perl idiom of cascading "elif (c=re_expr_match("..."))" blocks.

(I thought about cacheing previously seen REs, or adding support for
compiled REs instead of just strings - after all, this idiom usually
occurs in a loop while iterating of some large body of text.  It turns
out that the re module already caches previously compiled REs, so I
left my cacheing out in favor of that already being done in the std
lib.)

-- Paul

import re

class REmatcher(object):
def __init__(self,sourceline):
self.line = sourceline
def __call__(self, regexp):
self.matchresult = re.match(regexp, self.line)
self.success = self.matchresult is not None
return self.success
def __getattr__(self, attr):
return getattr(self.matchresult, attr)


This test:

test = """\
ABC
123
xyzzy
Holy Hand Grenade
Take the pebble from my hand, Grasshopper
"""

outfmt = "'%s' is %s [%s]"
for line in test.splitlines():
matchexpr = REmatcher(line)
if matchexpr(r"\d+$"):
print outfmt % (line, "numeric", matchexpr.group())
elif matchexpr(r"[a-z]+$"):
print outfmt % (line, "lowercase", matchexpr.group())
elif matchexpr(r"[A-Z]+$"):
print outfmt % (line, "uppercase", matchexpr.group())
elif matchexpr(r"([A-Z][a-z]*)(\s[A-Z][a-z]*)*$"):
print outfmt % (line, "a proper word or phrase",
matchexpr.group())
else:
print outfmt % (line, "something completely different", "...")

Produces:
'ABC' is uppercase [ABC]
'123' is numeric [123]
'xyzzy' is lowercase [xyzzy]
'Holy Hand Grenade' is a proper word or phrase [Holy Hand Grenade]
'Take the pebble from my hand, Grasshopper' is something completely
different [...]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread Emmanuel Surleau
On Saturday 04 April 2009 15:37:44 grkunt...@gmail.com wrote:
> I am a Java developer. There, I said it :-).
>
> When I am writing code, I can  rely on the compiler to confirm that
> any methods I write will be called with parameters of the "right"
> type. I do not need to test that parameter #1 really is a String
> before I call some method on it that only works on Strings.
>
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.

Well, it depends on what you're trying to do, really. You do *not* want to 
check parameters in every function. If you are designing a library, it is 
strongly advised to document what kind of parameters your functions 
expect. Otherwise, if your program will handle arbitrary input, you should 
check its format and reject it if it's invalid.

Cheers,

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


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread John Machin
On Apr 4, 3:21 pm, John Doe  wrote:
> Anybody have a solution for Windows (XP) Explorer search not finding
> ordinary text in *.py files?
>

Get a grep on yourself!

http://gnuwin32.sourceforge.net/packages/grep.htm

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


Re: Testing dynamic languages

2009-04-04 Thread andrew cooke
grkunt...@gmail.com wrote:
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.
>
> Is this the experience that Python programmer (of large projects) see?
> Do you also write unit tests to confirm that the methods actually
> check for and catch "bad" parameter types? If I am writing small one-
> off scripts, I wouldn't worry about it, but if I am writing a large
> system that must have 99+% uptime without constant monitoring, this
> really should be verified.

if you are going to do that, stay with java.  seriously - i too, am a java
developer about half the time, and you can make java pretty dynamic if you
try hard enough.  look at exploiting aspects and functional programming
libraries, for example.

the standard solution to what you describe (which is itself a standard
problem with dynamic languages) is unit testing.  proponents of dynamic
languages argue that you need to do testing anyway for its other
advantages.  proponents of statically typed languages argue that you need
to write more.  the best solution is probably to use a better language
(like ocaml or even haskell) (and i am only half joking).

asserting types isn't really going to work once you start exploiting just
what python can do (although look at abstract base classes - abcs - which
make things easier).

personally, i find that i write slightly more tests in python than java
and that my python code is, to be honest, slightly less reliable.  i also
add type assertions at critical points when refactoring (but otherwise
not).

so in summary:
- yes it's an issue
- solve it with more unit testing, not type assertions
- use the right tool for the job (which might be java)

all the above just my experience.  i tend to use java for the server side
and python for getting data into the database, so each plays to its
strengths.

andrew


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


Re: statvfs clearance

2009-04-04 Thread Hrvoje Niksic
Sreejith K  writes:

> Python's statvfs module contains the following indexes to use with
> os.statvfs() that contains the specified information
>
> statvfs.F_BSIZE
> Preferred file system block size.
[...]
> statvfs.F_NAMEMAX
> Maximum file name length.
>
> Can anyone tell me (or give me some links to know) what are these
> values ? The first three I know, I need to know about the rest

You can simply print them, they are integers:

>>> import statvfs
>>> statvfs.F_FLAG
8
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >