Re: ActivePython 2.6.1.1 and 3.0.0.0 released!

2008-12-12 Thread M�ta-MCI (MVP)

Hi!

M. Hammond said (wrote) said that the work is enormous, because 
modifications of the C architecture of Python 3 was largely modified.


(sorry for my bad english)
--
Michel Claveau

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


Re: Preventing execution of a method

2008-12-12 Thread boyombo
On Dec 12, 9:09 am, Bruno Desthuilliers  wrote:
> Emanuele D'Arrigo a écrit :
>
> > On Dec 11, 7:48 pm, Bruno Desthuilliers
> >  wrote:
> >>> or to provide read-only
> >>> access. I.e. right now I'm working on the graphical client which
> >>> potentially could be rewritten entirely by the users. It is necessary
> >>> and perfectly reasonable for the client module to access some of the
> >>> objects to be represented graphically, but those objects shouldn't be
> >>> modifiable by it.
> >> Why so ? At worst, they'll break everything.
>
> > -IF- the application was single-user yes, it wouldn't be a big deal.
> > But as it is potentially multi-user, I don't want one party to corrupt
> > the application for everybody else.
>
> A multi-users application with a GUI usually implies that it's a
> client-server app with the GUI deployed is on each client and the domain
> logic hosted on the server.

This is assuming the 'BAD GUY' does not have access to the server
code, right?
--
http://mail.python.org/mailman/listinfo/python-list


Re: HGE and Python (again)

2008-12-12 Thread Cro
Good day.

Thank you so much for your answer Diez!

I managed to call HGE dll the way you told:
>>> HGE = windll.LoadLibrary("C:/hge181/hge")
>>> HGE.hgeCreate(0x180)
But it's not helpful. It would mean that i have to re-create all the
header files from "include" directory in python, and all helper
functions from the "libs" to be able to use hge in the same way as the
original.
So ctypes is not what i need. It's a big step!

I also tried swig, a lot.
A lot, a lot, a lot of examples. Hacking examples and stuff.
And i managed to compile "hge.h" header and call the structs and HGE
main class. I don't seem to be able to acces the "enums", but that's
not a big problem.
How i did that, if anyone wants to know: There are 4 files.
- There is "example.cxx", that includes "hge.h" in the proper C++ way
and defines a HGE* hge=0 just like in the tutorials.
- Then is "hge.h", the original file, with ONE line commented: line
408 with the DLL EXPORT. Ah, and one more thing. I had to delete ALL
"CALL" keywords from HGE class, because if one CALL appears, the swig
compiler flags the line as error. So, for now, no stdcall.
- Then is "example.i", with "#include "hge.h"" and "%include "hge.h"".
Simple as that.
- And then, there is setup.py. "example_module = Extension('_example',
sources=['example_wrap.cxx', 'example.cxx'],)"
That's it. I compile it all like this:

swig -c++ -python example.i
setup build_ext --inplace

So it's a huge step for me. The compiler i have in my system is
mingw-3.4.5. I don't know if it's good for this. Maybe i should try a
MS compiler instead?

Next things i want to do:
- try to compile the project with a MS compiles. Visual studio 7.1 or
somethin.
- learn if i can do stdcalls from swig !!! This is the most important.
- try to compile one normal hge tutorial WITHOUT including "hge.lib"
and "hgehelp.lib". All functions defined there can be included just
like normal headers, the source is there and i compiled the libs
myself. I need this step because i don't think i can include lib files
in a swig project.
- try to do all i did in swig, with Cython. It's pretty easy to use
and faster from what i know.

So i must learn to to stdcalls from swig.
Can anyone suggest how to do that?

I mean, i have lines like:
virtual void CALL Release(); // in HGE class.
And:
void CALL HGE_Impl::Release()
{
//... // In the "c" file.
}
, where CALL is defined as "#define CALL __stdcall".
I simply can't make this kind of classes so work in swig.

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


using google search api for python

2008-12-12 Thread Matt
You might want to try this Google Search API for
Python.


Sample implementation:

>>> from Google import Google, search
>>> results = search('blackcodeseo.com', 3)
>>> for result in results:
… print 'Title: %s' % (result.title())
… print 'Url: %s' % (result.url())
… print 'Description: %s' % (result.description())
… print
…
Title: Black Code SEO
Url: http://blackcodeseo.com/
Description: Oct 29, 2008 … Black Code SEO. Programatically Automating SEO …
Download BlackCodeSeo Navigator. Run python setup.py install …

Title: Have A Question?
Url: http://blackcodeseo.com/have-a-question/
Description: If you have any questions about anything, you can reach me at
m...@blackcodeseo. com and I will be happy to reply. Your questions may be
posted on the site …

Title: SpiderMonkey « Didier Stevens
Url: http://blog.didierstevens.com/programs/spidermonkey/
Description: The exact post is
http://blackcodeseo.com/python-spidermonkey-navigator/. Comment by Matt —
Wednesday 29 October 2008 @ 20:56. Thanks. …

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


Re: Python, threading

2008-12-12 Thread Aahz
In article ,
SMALLp   wrote:
>
>Hy. I have a problem! I'm making multi thread application (client, 
>server) using wxPython for GUI, and threading.Thread for threding.
>
>Clients connect and when they are connected (evry thread handles one 
>connection) threads change main window.
>
>I neded tip how to make communication between threeds.

http://www.pythoncraft.com/OSCON2001/index.html
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Deeper tracebacks?

2008-12-12 Thread R. Bernstein
"Gabriel Genellina"  writes:
..

> No, last_traceback is the last *printed* traceback in the interactive
> interpreter. 

Well more precisely the traceback that is passed to sys.excepthook()
when an unhandled exception occcurs, since the hook that might not
decide to print anything ;-)

> Use the third element in sys.exc_info() instead:

Hmm...  I'm not sure what I was thinking when I read that way back
when, but you are correct and caught a bug in my code. I really do
need to do better about writing tests. Maybe next
incarnation... Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bidirectional Networking

2008-12-12 Thread Bryan Olson

Emanuele D'Arrigo wrote:

All the examples though are based on a client interrogating a server,
with the client initiating the connection, obtaining something and
then closing the connection. Basically the server is a reactive party:
only if the client get in touch the server respond.


Indeed, to the network programmer that pattern of interaction defines 
client/server (according to Douglas Comer's /Internetworking with TCP/IP).



What if the server
wanted to notify the client of something of interest, i.e. new data
that the client should take into consideration and potentially
process?


The "server push" problem.


One option would be for the client to periodically poll the server for
changes. Fair enough, that would work. But it'd be a bit of a waste if
the changes aren't particularly frequent.


Implementing server push on top of client poll is the most popular and 
generally simplest option.



Is it possible then to establish both a server and a client in the
same application?


Possible, and not all that hard to program, but there's a gotcha. 
Firewalls, including home routers and software firewalls, typically 
default to disallowing connections in the 'wrong' direction. If the 
client initiates all connections, you avoid a world of hassles.



I guess it must be possible but the examples all
rely on some kind of server loop (i.e. SocketServer.serve_forever)
that if started on both client and server sides would create two
listening parties but no talking at all! Furthermore, other libraries
might have their own loop, i.e. a graphical client has a loop to
redraw the screen and the two loops would somehow have to be
interleaved.

I'm not quite seeing how this can be done other than we threads. Is
that the way to do it? Place the listening loop in a thread while the
rest of the application does its own thing?


Threads work. Other options in Python standard library are 'select' and 
'asyncore', but these do not play well with SocketServer and its 
descendants. There are also other free Python libraries.



Or is it SocketServer.handle_request() the key? I could call this
function periodically, but what happens if a request is made while the
application is doing something else? Are the requests queued and dealt
with one per loop?


Requests are queued up, but the queue is small. SocketServer is built on 
top of 'socket', which has the list() and accept() calls to create the 
queue and get connections from it, respectively. The traditional listen 
queue size, and sometimes the system maximum, is 5.


If you want to use SocketServer, read about ThreadingMixIn and ForkingMixIn.


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


Re: ActivePython 2.6.1.1 and 3.0.0.0 released!

2008-12-12 Thread Kay Schluehr
On 13 Dez., 00:16, Trent Mick  wrote:

> Note that currently PyWin32 is not included in ActivePython 3.0.

Is there any activity in this direction?
--
http://mail.python.org/mailman/listinfo/python-list


Re: forcing future re-import from with an imported module

2008-12-12 Thread Gabriel Genellina
En Fri, 12 Dec 2008 19:44:32 -0200, _wolf   
escribió:



On Dec 11, 12:43 am, rdmur...@bitdance.com wrote:

"Why can't you have the code that is doing the import [...]
call a function [...] to produce [the] side effect [...]?
Explicit is better than implicit.  A python programmer is
going to expect that importing a module is idempotent"


you’re completely right that `import foo` with side effects may break
some expectations, but so do all `from __future__` imports. you’re
also right that another solution would be to come in from the other
side and explicitly call a function from the importing module. all of
this does not answer one question tho: why does deleting a module work
most of the time, but not in the case outlined in my first post,
above? why do we get to see this slightly strange error message there
complaining about ‘not finding’ a module ‘in sys.modules’—well, most
of the time, when a module is not in that cache, it will be imported,
but not in this case. why?


The import system can be customised in many ways (the various import  
hooks, special entries in sys.path, meta_path, path_hooks, __import__,  
etc.), even could be completely reimplemented. There are safety checks in  
the interpreter, to validate some minimal pre and postconditions that  
should always hold.
By example, checking that sys.path contains a list of directories. Or the  
one you broke: after successfully executing "import foo", there must be an  
entry named "foo" in sys.modules. If not, it is asumed that something in  
the import machinery went wrong.


--
Gabriel Genellina

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


Re: Py_GetPath() C API in python 3

2008-12-12 Thread Gabriel Genellina

En Fri, 12 Dec 2008 04:50:06 -0200, stalex  escribió:


I want to build a new, requires total control, python interpreter. So
I implement my own version of Py_GetPath(), Py_GetPrefix(),
Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I
always get error messages, for each API function, look like
followings:

/opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text
+0x211c): In function `Py_GetPath':
./Modules/getpath.c:739: multiple definition of `Py_GetPath'
myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first
defined here
/usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in
system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a
(getpath.o)
collect2: ld returned 1 exit status


Looks like you added your own implementation of those functions  
(/home/alex/...myApp.c) but forgot to remove the original one  
(Modules/getpath.c)


--
Gabriel Genellina

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


Re: var or inout parm?

2008-12-12 Thread Hrvoje Niksic
sturlamolden  writes:

> What? Take a look at the code again:
>
> mytuple[0] += 1
>
> should never attempt an __iadd__ on mytuple.
>
> A sane parser would see this as:
>
> tmp = mytuple.__getitem__(0)
> tmp = tmp.__iadd__(1)
> mytuple.__setitem__(0, tmp) # should this always raise an exception?

What do you mean by "a sane parser"?  This is exactly what happens in
current Python.  Since tuple's __setitem__ always raises an exception
(and that is by design and not likely to change), everything is sane.

Saner (in this respect) behavior in the tuple example would require a
different protocol.  I don't understand why Python doesn't just call
__iadd__ for side effect if it exists.  The decision to also rebind
the result of __i*__ methods continues to baffle me.  I guess it is a
result of a desire to enable the __i*__ methods to punt and return a
different instance after all, but if so, that design decision brings
more problems than benefits.
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Scott David Daniels

feb...@gmail.com wrote:

...
elif bank >= 1 and bank <= 24999:
rate = 0.0085

> ...

Also, (although not useful here as others have pointed out),
note that particular code means the same thing as:
...
elif 1 <= bank <= 24999:
rate = 0.0085
...


--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I manually uninstall setuptools (installed by egg)?

2008-12-12 Thread David Cournapeau
On Sat, Dec 13, 2008 at 1:30 AM, Nick Craig-Wood  wrote:
> David Cournapeau  wrote:
>>  On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood  
>> wrote:
>> > David Cournapeau  wrote:
>> >>  On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert  wrote:
>> >> > On Tue, Dec 9, 2008 at 6:49 PM,   wrote:
>> >> >> On Ubuntu, I accidentally manually installed setuptools
>> >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file
>> >> >> as a shell script via sudo), and now realize I should just be using
>> >> >> apt to take care of my system Python packages.
>> >> >
>> >> > Really, why? setuptools has more Python packages/programs available
>> >> > and updates faster than Debian.
>> >> > It's also likely that some of the Debian Python packages are installed
>> >> > using setuptools anyway.
>> >> > So, why do you think apt and not setuptools is The Right Way(tm)?
>> >>
>> >>  Setuptools is certainly not the right way to install packages
>> >>  system-wide on debian, it is very likely to break the whole thing.
>> >
>> > It wouldn't be too difficult to make a .deb target which would collect
>> > all the files that did get installed into a package.  It would be a
>> > rather rough and ready package but would do the job.
>>
>>  Depends what you mean by would do the job: rather rough certainly does
>>  not mean "would do the job" for something as essential as a package
>>  IMO.
>
> Essentially a package has files in it in a fixed possition in the
> filesystem.  The package manager's (dpkg at this level) job is to keep
> track of those file and tell you about conflicts.

Yes, but this description is so high level that it hides the
difficulty of the task :) First, and firstmost, it is difficult if not
impossible to automatically translate from distutils/setuptools file
locations to a typical debian (or most other distribution for that
matter - the one which follow the FHS) description. Because distutils
does not make the distinction between doc, data, etc... as well as for
example autotools does.

>
> You can use alien to turn a tar.gz into a perfectly usable debian
> package.  It won't have dependencies, or help or any of the other
> things a package needs to be a proper package, but it satisfies my
> basic needs that all software is installed as packages, so it can be
> uninstalled cleanly.

This only works for very simple packages - pure python or no
dependencies, no post/pre install scripts, etc... If you want to
install a web framework, it won't be enough. If you want to install a
package which depends on C libraries, it won't work either.

>
> However when I have to make my stuff work on Windows, I find
> easy_install to be a fantastic timesaver as compared to looking for
> the package on a web site, downloading it, unpacking it installing it
> and then repeating for all the dependencies.

I agree that its features are useful. I just don't think the
implementation and the design are right - partly because it inherits
some fundamental distutils deficiencies with respect to package
description.

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


Re: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop.

2008-12-12 Thread David Boddie
On Friday 12 December 2008 02:05, Mudcat wrote:

> The drag is working up until the point I try to actually retrieve the
> data. At that point I get an unhandled Runtime Error saying "no access
> to protected functions or signals for objects not created in Python".

That's correct, retrieveData() is a protected function in C++ and the
QMimeData object was created by the framework, not you, in this case.

> Obviously I am not retrieving them in the correct format. Does anyone
> know how to convert/retrieve the information into a Python list?

You could use the data() method to get the serialized data then try to
extract the list item-by-item using the QDataStream class, or perhaps
PyQt has a convenience function to unpack the items.

Alternatively - and this is a bit speculative - perhaps you can copy
the data to another QMimeData object which you have created, and use
its retrieveData() method to retrieve the items.

You might get a more detailed response by asking on the PyQt mailing list:

  http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Hope this helps,

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


Re: __future__ and unrecognised flags

2008-12-12 Thread Terry Reedy

Poor Yorick wrote:

I have a future statement in a script I intend to work on 2.6 and 3.  Shouldn't 
__future__ statements basically be noops for versions that already support the 
feature? doctest is complaining about compiler flags.  This illustrates the 
problem:

Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] 
on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> src = 'a = "hello"'
>>> c1 = compile(src,'','exec',unicode_literals.compiler_flag)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: compile(): unrecognised flags


According to this "The optional arguments flags and dont_inherit control 
which future statements (see PEP 236) affect the compilation of source. 
If neither is present (or both are zero) the code is compiled with those 
future statements that are in effect in the code that is calling 
compile. " you do not need to duplicate the future option in the compile 
call.


I tried doing the same without the flag and it works.  That said, this 
seems like a bug to me, so if no one explains otherwise, report it at

http://bugs.python.org

I tried with 5th param True and got same error.

On Winxp

tjr




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


Re: Bidirectional Networking

2008-12-12 Thread James Mills
Just as a matter of completeness for my own suggestion, here
is my implementation of your code (using circuits):

cheers
James

--

import random
from circuits import listener, Event, Manager
from circuits.lib.sockets import TCPServer, TCPClient

class Server(TCPServer):

   channel = "server"

   @listener("read")
   def onREAD(self, sock, data):
  print "-> RECV: %s - Sent by: %s" % (data, hsot)

class Client(TCPClient):

   channel = "client"

   def __init__(self, remoteServer):
  super(Client, self).__init__()
  self.cycle = 0
  self.randomNumber = 0
  self.message = None
  self.remoteServer = remoteServer

   @listener("connect")
   def onCONNECT(self, host, port):
  self.write(self.message)
  print "SENT ->: %d by by local cycle %d" % (self.randomNumber, self.cycle)
  self.close()
  self.success = True

   @listener("disconnect")
   def onDISCONNECT(self):
  if not self.success:
 print "Failed to send number on cycle %d " % self.cycle
 self.success = None

   @listener("cycle")
   def onCYCLE(self):
  if self.cycle < 1000:
 chance = random.random()

 if (chance < 0.01):
self.randomNumber = int(random.random() * 1000)
self.message = "%d from remote cycle %d" % (self.randomNumber,
  self.cycle)
self.open(*self.remoteServer)
self.cycle += 1

 manager.push(Event(), "cycle", "client")

localServer = (, "localhost")
remoteServer = ("localhost", 1)

manager = Manager()

server = Server(*localServer)
client = Client(remoteServer)

manager += server
manager += client

manager.push(Event(), "cycle", "client")

while True:
   try:
  server.poll()
  client.poll()
  manager.flush()
   except KeyboardInterrupt:
  client.close()
  break
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread Steven D'Aprano
On Fri, 12 Dec 2008 08:43:31 -0800, sturlamolden wrote:

> On Dec 12, 5:13 pm, Steve Holden  wrote:
> 
>> > It should be the tuple's __setitem__ that was invoked here, not
>> > __iadd__, or the parser is faulty.
>>
>> OK, so now you are proposing to alter the parser, and possibly the
>> implementation of the INPLACE_ADD opcode in eval.c, so can you give us
>> the patch for those, please?
> 
> What? Take a look at the code again:
> 
> mytuple[0] += 1
> 
> should never attempt an __iadd__ on mytuple.
> 
> A sane parser would see this as:
> 
> tmp = mytuple.__getitem__(0)
> tmp = tmp.__iadd__(1)
> mytuple.__setitem__(0, tmp) # should this always raise an exception?

It is quite problematic if you do that. You've already pointed that out 
yourself, by asking if "should this always raise an exception?". With the 
behaviour you're asking for, there's ambiguity is what is allowed and 
what isn't. You can try making __setitem__ cleverer, as in your earlier 
post, but then:

t = (1, 2, 3)
t[0] += x

sometimes succeeds, sometimes fails, depending on the value of x.

And worse:

t[0] = y

also sometimes succeeds.

It's not clear that those occasional successes are actively harmful, but 
nor is it clear that prohibiting them is harmful either. The best you get 
from it is the ability to mutate mutable items in a tuple, but you can do 
that already:

t = ([], None)
x = t[0]
x += ["mutated"]

So the current tuple implementation gives us consistent behaviour and 
simplicity without preventing you from mutating elements if you really 
want to. The only real cost is if you do this:

t[0] += ["mutated"]

you get an error and a mutation. Certainly a gotcha, but I wouldn't 
describe it as a bug: it's pretty much unavoidable if you want to avoid 
treating tuples as a special case.



>> Discussion of such behavior as a "bug" is also pejorative, since the
>> current semantics are the way they are by design.
> 
> Right, this bug is by design. You learned that phrase from a guy in
> Redmond?

No. It merely means that just because you think it is a bug doesn't make 
it so. It may even mean that there is no perfect solution, that *any* 
behaviour on tuples containing mutable objects will be considered broken 
by some people under some circumstances.

Trade-offs in software design are inevitable. There's little gain from 
your proposal, and some cost, and the problem you are trying to solve 
isn't a problem in practice. So if it's a bug, it's an insignificant one, 
not worth fixing because the fix will invariably cause more problems than 
the bug.



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


Re: Removing None objects from a sequence

2008-12-12 Thread Terry Reedy

Tim Chase wrote:
If you want to literally remove None objects from a list(or 
mutable sequence)


def deNone(alist):
   n=len(alist)
   i=j=0
   while i < n:
 if alist[i] is not None:
   alist[j] = alist[i]
   j += 1
 i += 1
   alist[j:i] = []

blist=[None,1,None,2,None,3,None,None,4,None]
deNone(blist)
print(blist)

# prints [1, 2, 3, 4]


...wouldn't a cleaner way of doing this just be

  >>> blist=[None,1,None,2,None,3,None,None,4,None]


No, making a filtered copy that is then copied back before being deleted 
is algorithmically much messier.  My code does the minimum work 
necessary and is algorithmically cleaner.



  >>> alist = blist
  >>> blist[:] = [x for x in blist if x is not None]
  >>> blist
  [1, 2, 3, 4]
  >>> alist
  [1, 2, 3, 4]

By using the slice assignment, it leaves the blist referring to the same 
list-object (as shown by the "alist" bit), and modifying it in place.  
This reads a lot more cleanly in my estimation.


If the data-set is large, in 2.5+, you can just use a generator:

  blist[:] = (x for x in blist if x is not None)


Given that this works, that the setup for slice assignment does not mess 
up the co-routine iteration over the same loop, this is pretty good.  It 
amounts to deNone with the i-j loop separated into an i loop and a j 
loop in source and consumer co-routines.  One could argue that that is 
even better, even if written out as


def deNone2(alist):
  src = (item for item in alist if item is not None)
  j=0
  try:
while True:
  alist[j] = next(src)
  j += 1
  except StopIteration:
pass
  alist[j:] = []

tjr

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread bearophileHUGS
Kirk Strauser:

> def get_rate(balance):
>for threshold, rate in ((10, .0173),
>(5, .0149),
>(25000, .0124),
>(1, .0085),
>(0, .006)):
>if balance > threshold:
>return rate
>return .0

Nice code. This operation, of choosing an item in a sorted list of
intervals that has no holes, is common enough. But something like an
interval dict is overkill here.
I suggest to put a zero before all those points, to improve
readability and avoid some possible errors: it's easy to not see a
small leading point.



Bruno Desthuilliers:

> A sequence of pairs and a dict are _almost_ interchangeable (mmm... is
> that the correct word ?) representations of a same data set[1] - the
> main difference being ordering. If ordering matters, choose a sequence
> of pairs as main representation - you can easily build a dict from it
> if/when you need it.

Generally(*) it's better to use the simpler data structure that does
the job. Here a list/tuple of tuples is good.
Very often programs get translated to other languages, so keeping
things as simple as possible helps that too.

-

(*) I have used 'generally' because there's a compromise to be taken
here.

In C and other related languages you often use structs or records, so
if you have pairs you give a name to the fields, for example "x" and
"y" for the two coordinates of a 2D Point. In Python in such situation
you can create a Point class, but often you instead use a (x, y) or
[x, y]. In some situations you need to access the fields, so you use
[0] and [1]. This is (was) a case where Python looks lower-lever than
the C language. In Python3/Python2.6+ you can use a NamedTuple too.

Is it better to give and take a list of points to/from as a list of
[x,y] lists or as a list of Point2D? Probably a Java programmer thinks
that using Point2D is safer and is a way to document what the function
takes/returns too. Extending the list of pairs to 3D points is a
little simpler if they are represented as tuples/lists.

That's an example where you may not choose the simpler data structure
(that in Python is a list of pairs) and use a list of NamedTuple to
make code "safer" even if the data structure is a little more complex.

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


Re: Removing None objects from a sequence

2008-12-12 Thread Erik Max Francis

Filip Gruszczyński wrote:


I don't mean memory, but space in code ;-)


Your goal should be clarity of code, not saving keystrokes.  Writing 
something that is compact in terms of the amount of code to write does 
not mean its function is clear or even that it is more efficient to run, 
for that matter.


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  God grant me to contend with those that understand me.
   -- Thomas Fuller
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.lstat : proper way to do this

2008-12-12 Thread MRAB

m1k...@gmail.com wrote:

I'm converting from Perl to Python, so I'm learning the basics -
please be gentle! :)

In Perl, I can lstat($file) whether $file exists or not:
lstat($file);
unless (-e _) {
print STDERR "$file: No such file or directory\n";
}
unless (-l _) {
print STDERR "$file: Not a symbolic link\n";
}

The lstat() returns normally whether the file exists or not, and I
check for existence with the "-e" conditional. Then I go on and check
other modes.

In Python,if I os.lstat(file) and file doesn't exist, I get an error
from within the module:
OSError: [Errno 2] No such file or directory: '/etc/xxx'

I can check first with os.path.exists(file), but then I'm doing two
stat() type calls which is inefficient (especially when we're talking
thousands of files).

I want to be able to do something like this:
mode = os.lstat(file)[ST_MODE]
if not mode:
print >> sys.stderr, file, ": No such file or directory"
if not S_ISLNK(mode):
print >> sys.stderr, file, ": Not a symbolic link"

Of course, this isn't valid. How can I do this efficiently without
getting "no such file" error?


Just catch the exception:

try:
mode = os.lstat(file).st_mode # An alternative way.
# If we get here then the file does exist.
if not S_ISLNK(mode):
print >> sys.stderr, file, ": Not a symbolic link"
except OSError, e:
if e.errno == 2:
# File doesn't exist.
print >> sys.stderr, file, ": No such file or directory"
else:
# Failed for some other reason.


BTW, "file" happens to be the name of one of the build-ins, so try to 
use something else, eg. "file_path".

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


Re: os.lstat : proper way to do this

2008-12-12 Thread Benjamin Kaplan
On Fri, Dec 12, 2008 at 6:06 PM,  wrote:

> I'm converting from Perl to Python, so I'm learning the basics -
> please be gentle! :)
>
> In Perl, I can lstat($file) whether $file exists or not:
> lstat($file);
> unless (-e _) {
>print STDERR "$file: No such file or directory\n";
> }
> unless (-l _) {
>print STDERR "$file: Not a symbolic link\n";
> }
>
> The lstat() returns normally whether the file exists or not, and I
> check for existence with the "-e" conditional. Then I go on and check
> other modes.
>
> In Python,if I os.lstat(file) and file doesn't exist, I get an error
> from within the module:
> OSError: [Errno 2] No such file or directory: '/etc/xxx'
>
> I can check first with os.path.exists(file), but then I'm doing two
> stat() type calls which is inefficient (especially when we're talking
> thousands of files).
>
> I want to be able to do something like this:
> mode = os.lstat(file)[ST_MODE]
> if not mode:
>print >> sys.stderr, file, ": No such file or directory"
> if not S_ISLNK(mode):
>print >> sys.stderr, file, ": Not a symbolic link"
>
> Of course, this isn't valid. How can I do this efficiently without
> getting "no such file" error?
>

In Python, people usually follow the "Easier to Ask Forgiveness than
Permission" philosophy. Rather than prevent an error from occurring, just
let it happen and deal with if when it does. Wrap your call to os.lstat in a
try/except block and just print your error message if the lstat call fails.
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread Chris Rebert
On Fri, Dec 12, 2008 at 4:56 AM, sturlamolden  wrote:
> On Dec 12, 1:44 pm, "Chris Rebert"  wrote:
>
>> Python begs to differ, as those two statements are both semantically
>> identical in this case:
>
> That is because integers are immutable. When x += 1 is done on an int,
> there will be a rebinding. But try the same on say, a numpy array, and
> the result will be different:

Yes, I know that. Did you not read the end of my email? Here it is again:

"""
If you were talking about lists rather than integers though, you'd be
absolutely correct, as the += ends up being a method call to __iadd__
instead of a plain assignment.
"""

Cheers,
Chris

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


ActivePython 2.6.1.1 and 3.0.0.0 released!

2008-12-12 Thread Trent Mick
I'm happy to announce that ActivePython 2.6.1.1 and ActivePython 3.0.0.0 
are now available.


Details and download links for 2.6 here:
  http://www.activestate.com/Products/activepython/feature_list.mhtml

Details and download links for 3.0 here:
  http://www.activestate.com/Products/activepython/python3.mhtml

All ActivePython downloads (e.g. for older releases) are available here:
  http://downloads.activestate.com/ActivePython/


ActivePython 3.0.0.0 is the first release of ActivePython for Python 3. 
ActivePython 2.6.1.1 is a patch release based on Python 2.6.1.



What is ActivePython?
-

ActivePython is ActiveState's binary distribution of Python. Builds for
Windows, Mac OS X, Linux, HP-UX and AIX are made freely available.

ActivePython includes the Python core and the many core extensions: zlib
and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite
(sqlite3) database libraries, OpenSSL bindings for HTTPS support, the
Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on
supported platforms) for low-level library access, and others.

The Windows distribution ships with PyWin32 -- a suite of Windows tools
developed by Mark Hammond, including bindings to the Win32 API and
Windows COM. Note that currently PyWin32 is not included in ActivePython 
3.0. See this page for full details:

  http://docs.activestate.com/activepython/2.6/whatsincluded.html
  http://docs.activestate.com/activepython/3.0/whatsincluded.html

As well, ActivePython ships with a wealth of documentation for both new
and experienced Python programmers. In addition to the core Python docs,
ActivePython includes the "What's New in Python" series, "Dive into
Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals
(PEPs).

An online version of the docs can be found here:
http://docs.activestate.com/activepython/2.6/welcome.html

We would welcome any and all feedback to:
activepython-feedb...@activestate.com.com

Please file bugs against ActivePython at:
http://bugs.activestate.com/query.cgi?set_product=ActivePython



On what platforms does ActivePython run?


ActivePython includes installers for the following platforms:

- Windows/x86
- Mac OS X
- Linux/x86
- Linux/x86_64 ("x86_64" is also known as "AMD64")
- Solaris/SPARC
- Solaris/SPARC (64-bit)
- Solaris/x86
- HP-UX/PA-RISC
- AIX/PowerPC


Extra Bits
--

ActivePython releases also include the following:

- ActivePython26.chm & ActivePython30.chm: An MS compiled help
  collection of the full ActivePython documentation set. Linux users of
  applications such as xCHM might find this useful. This package is
  installed by default on Windows.

Extra bits are available from:
http://downloads.activestate.com/ActivePython/etc/


Thanks, and enjoy!

Trent, Python Tech Lead

--
Trent Mick
http://planet.activestate.com/
trentm at activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


os.lstat : proper way to do this

2008-12-12 Thread m1k3b0
I'm converting from Perl to Python, so I'm learning the basics -
please be gentle! :)

In Perl, I can lstat($file) whether $file exists or not:
lstat($file);
unless (-e _) {
print STDERR "$file: No such file or directory\n";
}
unless (-l _) {
print STDERR "$file: Not a symbolic link\n";
}

The lstat() returns normally whether the file exists or not, and I
check for existence with the "-e" conditional. Then I go on and check
other modes.

In Python,if I os.lstat(file) and file doesn't exist, I get an error
from within the module:
OSError: [Errno 2] No such file or directory: '/etc/xxx'

I can check first with os.path.exists(file), but then I'm doing two
stat() type calls which is inefficient (especially when we're talking
thousands of files).

I want to be able to do something like this:
mode = os.lstat(file)[ST_MODE]
if not mode:
print >> sys.stderr, file, ": No such file or directory"
if not S_ISLNK(mode):
print >> sys.stderr, file, ": Not a symbolic link"

Of course, this isn't valid. How can I do this efficiently without
getting "no such file" error?

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


Re: Removing None objects from a sequence

2008-12-12 Thread Steven D'Aprano
On Fri, 12 Dec 2008 21:18:36 +, Lie Ryan wrote:

> On Fri, 12 Dec 2008 11:50:38 -0500, Steve Holden wrote:
> 
>> Kirk Strauser wrote:
>>> At 2008-12-12T15:51:15Z, Marco Mariani  writes:
>>> 
 Filip Gruszczyński wrote:

> I am not doing it, because I need it. I can as well use "if not elem
> is None",
>>> 
 I suggest "if elem is not None", which is not quite the same.
>>> 
>>> So what's the difference exactly?  "foo is not None" is actually
>>> surprising to me, since "not None" is True.  "0 is True" is False, but
>>> "0 is not None" is True.  Why is that?
>> 
>> "is not" is an operator, so the parse is
>> 
>> foo (is not) None
>> 
>> not
>> 
>> foo is (not None)
>> 
>> 
> Personally, I'd prefer VB's version:
> foo IsNot bar
> 
> or in pseudo-python
> foo isnot bar
> 
> since that would make it less ambiguous.

"a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity 
if you are ignorant of the precedence rules, but that's no worse than 
saying that "+" is ambiguous if you don't know what "+" means.

"What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!! 
Panic panic panic panic!!!"

*wink*

You're allowed to assume the normal conventions, and (lucky for me!) 
despite being Dutch Guido choose to assume the normal English convention 
that "a is not b" means the same as "not (a is b)" rather than "a is (not 
b)". That's probably because the use-cases for the second would be rather 
rare.

So given the normal precedence rules of Python, there is no ambiguity. 
True, you have to learn the rules, but that's no hardship.



-- 
Steven

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


Re: concept of creating structures in python

2008-12-12 Thread Steven D'Aprano
On Fri, 12 Dec 2008 09:07:21 -0700, Joe Strout wrote:

>> Joe missed a piece out here. If you change the signature of your
>> D.__init__() to read
>>
>> def  __init__(self, dataName='ND', index = 0, ele_obj=None):
>>
>> then you need to insert the following code at the top of the method:
>>
>>if ele_obj is None:
>>ele_obj = E()
> 
> Yes, if you really need to guarantee that ele_obj is not None, then this
> is the way to do it.
> 
> Of course this would mean that you can't get a None ele_obj even by
> passing it in explicitly as the parameter value -- if you need to
> support that as well, then the solution is a little more complex.
> Perhaps best in that case would be to just not give ele_obj any default
> value at all, so it becomes a required parameter.


Just use a sentinel that isn't None.


class D(...):
sentinel = object()
def __init__(self, dataName='ND', index = 0, ele_obj=sentinel):
if ele_obj is D.sentinel:
...


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


Re: Removing None objects from a sequence

2008-12-12 Thread Steven D'Aprano
On Fri, 12 Dec 2008 10:08:23 -0600, Kirk Strauser wrote:

> At 2008-12-12T15:51:15Z, Marco Mariani  writes:
> 
>> Filip Gruszczyński wrote:
>>
>>> I am not doing it, because I need it. I can as well use "if not elem
>>> is None",
> 
>> I suggest "if elem is not None", which is not quite the same.
> 
> So what's the difference exactly?  "foo is not None" is actually
> surprising to me, since "not None" is True.  "0 is True" is False, but
> "0 is not None" is True.  Why is that?

"a is not b" uses a single operator to do the test.

>>> import dis
>>> x = compile('a is not b', '', 'single')
>>> dis.dis(x)
  1   0 LOAD_NAME0 (a)
  3 LOAD_NAME1 (b)
  6 COMPARE_OP   9 (is not)
  9 PRINT_EXPR
 10 LOAD_CONST   0 (None)
 13 RETURN_VALUE


"not a is b" looks like it would use two operators (is, followed by not) 
but wonderfully, Python has a peephole optimization that fixes that micro 
inefficiency: 


>>> x = compile('not a is b', '', 'single')
>>> dis.dis(x)
  1   0 LOAD_NAME0 (a)
  3 LOAD_NAME1 (b)
  6 COMPARE_OP   9 (is not)
  9 PRINT_EXPR
 10 LOAD_CONST   0 (None)
 13 RETURN_VALUE



So if you are using at least Python 2.5, the two expressions don't just 
return the same result, they actually generate the same byte code.


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


Re: Removing None objects from a sequence

2008-12-12 Thread Tim Chase
If you want to literally remove None objects from a list(or mutable 
sequence)


def deNone(alist):
   n=len(alist)
   i=j=0
   while i < n:
 if alist[i] is not None:
   alist[j] = alist[i]
   j += 1
 i += 1
   alist[j:i] = []

blist=[None,1,None,2,None,3,None,None,4,None]
deNone(blist)
print(blist)

# prints [1, 2, 3, 4]


...wouldn't a cleaner way of doing this just be

  >>> blist=[None,1,None,2,None,3,None,None,4,None]
  >>> alist = blist
  >>> blist[:] = [x for x in blist if x is not None]
  >>> blist
  [1, 2, 3, 4]
  >>> alist
  [1, 2, 3, 4]

By using the slice assignment, it leaves the blist referring to 
the same list-object (as shown by the "alist" bit), and modifying 
it in place.  This reads a lot more cleanly in my estimation.


If the data-set is large, in 2.5+, you can just use a generator:

  blist[:] = (x for x in blist if x is not None)

-tkc



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


Re: Removing None objects from a sequence

2008-12-12 Thread Terry Reedy
If you want to literally remove None objects from a list(or mutable 
sequence)


def deNone(alist):
  n=len(alist)
  i=j=0
  while i < n:
if alist[i] is not None:
  alist[j] = alist[i]
  j += 1
i += 1
  alist[j:i] = []

blist=[None,1,None,2,None,3,None,None,4,None]
deNone(blist)
print(blist)

# prints [1, 2, 3, 4]

Terry Jan Reedy

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


__future__ and unrecognised flags

2008-12-12 Thread Poor Yorick
I have a future statement in a script I intend to work on 2.6 and 3.  Shouldn't 
__future__ statements basically be noops for versions that already support the 
feature? doctest is complaining about compiler flags.  This illustrates the 
problem:

Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] 
on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> src = 'a = "hello"'
>>> c1 = compile(src,'','exec',unicode_literals.compiler_flag)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: compile(): unrecognised flags

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


Re: Interface & Implementation

2008-12-12 Thread Lie Ryan
On Fri, 12 Dec 2008 16:07:26 +0530, J Ramesh Kumar wrote:

> Hi,
> 
> I am new to python. I require some help on implementing interface and
> its implementation. I could not find any sample code in the web. Can you
> please send me some sample code which is similar to the below java code
> ? Thanks in advance for your help.
> 
> 
> public interface MyIfc
> {
> public void myMeth1();
> public void myMeth2();
> }
> 
> public class MyClass implements MyIfc {
>   public void myMeth1()
>   {
>   //do some implementation
>   }
> 
>  public void myMeth2()
>{
>//do some implementation
>}
> }

There is no need for interface in python due to duck typing 

class MyClass1(object):
def myMeth1(self): 
# some implementation
def myMeth2(self):
# some implementation
class MyClass2(object):
def myMeth1(self): 
# other implementation
def myMeth2(self):
# other implementation

cs[0] = MyClass1()
cs[1] = MyClass2()
for c in cs: 
c.myMeth1()
c.myMeth2()

but if you really want it, simple inheritance might be better anyway, 
though not really pythonic:

class MyIfc(object):
def myMeth1(self): return NotImplemented
def myMeth2(self): return NotImplemented
class MyClass(MyIfc):
def myMeth1(self): 
# some implementation
def myMeth2(self):
# some implementation

# some might notice the (ab)use of NotImplemented sentinel there

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


Re: forcing future re-import from with an imported module

2008-12-12 Thread _wolf
On Dec 11, 12:43 am, rdmur...@bitdance.com wrote:
> "Why can't you have the code that is doing the import [...]
> call a function [...] to produce [the] side effect [...]?
> Explicit is better than implicit.  A python programmer is
> going to expect that importing a module is idempotent"

you’re completely right that `import foo` with side effects may break
some expectations, but so do all `from __future__` imports. you’re
also right that another solution would be to come in from the other
side and explicitly call a function from the importing module. all of
this does not answer one question tho: why does deleting a module work
most of the time, but not in the case outlined in my first post,
above? why do we get to see this slightly strange error message there
complaining about ‘not finding’ a module ‘in sys.modules’—well, most
of the time, when a module is not in that cache, it will be imported,
but not in this case. why?

cheers & ~flow
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mathematica 7 compares to other languages

2008-12-12 Thread Bakul Shah

George Neuner wrote:

On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee 
wrote:


On Dec 10, 2:47 pm, John W Kennedy  wrote:

Xah Lee wrote:

In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java,
you'll have 50 or hundreds lines.

C:

#include 
#include 

void normal(int dim, float* x, float* a) {
float sum = 0.0f;
int i;
float divisor;
for (i = 0; i < dim; ++i) sum += x[i] * x[i];
divisor = sqrt(sum);
for (i = 0; i < dim; ++i) a[i] = x[i]/divisor;

}
i don't have experience coding C. 


Then why do you talk about it as if you know something?


The code above doesn't seems to satisfy the spec.


It does.


The input should be just a vector, array, list, or
whatever the lang supports. The output is the same 
datatype of the same dimension.


C's native arrays are stored contiguously.  Multidimensional arrays
can be accessed as a vector of length (dim1 * dim2 * ... * dimN).

This code handles arrays of any dimensionality.  The poorly named
argument 'dim' specifies the total number of elements in the array.

George


Only if the length in each dimension is known at compile time (or
in C99, if this is an automatic array). When this is not the case,
you may have to implement something like the following (not the only
way, just one way):

float** new_matrix(int rows, int cols) {
float** m = malloc(sizeof(float*)*rows);
int i;
for (i = 0; i < rows; i++)
m[i] = malloc(sizeof(float)*cols);
return m;
}

In this case normal() fails since matrix m is not in a single
contiguous area.

But I suspect Xah is complaining because the function doesn't
*return* a value of the same type; instead you have to pass in
the result vector. But such is life if you code in C!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Lie Ryan
On Fri, 12 Dec 2008 11:50:38 -0500, Steve Holden wrote:

> Kirk Strauser wrote:
>> At 2008-12-12T15:51:15Z, Marco Mariani  writes:
>> 
>>> Filip Gruszczyński wrote:
>>>
 I am not doing it, because I need it. I can as well use "if not elem
 is None",
>> 
>>> I suggest "if elem is not None", which is not quite the same.
>> 
>> So what's the difference exactly?  "foo is not None" is actually
>> surprising to me, since "not None" is True.  "0 is True" is False, but
>> "0 is not None" is True.  Why is that?
> 
> "is not" is an operator, so the parse is
> 
> foo (is not) None
> 
> not
> 
> foo is (not None)
> 

Personally, I'd prefer VB's version:
foo IsNot bar

or in pseudo-python
foo isnot bar

since that would make it less ambiguous.

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


Re: Testing against different versions of Python

2008-12-12 Thread Lie Ryan
On Fri, 12 Dec 2008 14:42:24 -0500, mercado wrote:

> What is the best way to go about testing against different versions of
> Python?  For example, I have 2.5.2 installed on my machine (Ubuntu Hardy
> 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly
> other versions as well).

definitely you need to have the test code first (unittest or doctest)

then it's just a matter of running a shell script (or python script with 
subprocess) to check if the code generated any errors in any version.

The problem might be how to install multiple sub-minor version of python. 
I often see a machine with multiple minor versions, but have no idea 
whether multiple sub-minor versions could coexists.

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


Re: Bidirectional Networking

2008-12-12 Thread Gabriel Genellina
En Fri, 12 Dec 2008 15:22:34 -0200, Emanuele D'Arrigo   
escribió:



Thank you both for the suggestions! Eventually I tried with threading
as illustrated in the code below.
And it works pretty well! The only problem I'm having with it is that
as the server is a daemon the program should end when the client
thread cease to be alive. But it doesn't seem to work that way and I'm
not sure what's going on! I did achieve my objective though. Two
separate instances of the code below will happily send random numbers
to each other for a few seconds!


If you're using 2.5 or older, override serve_forever:

def serve_forever(self):
while not getattr(self, 'quit', False):
self.handle_request()

and set the server 'quit' attribute to True in response to some command  
from the client.

Python 2.6 has a shutdown() method for the same purpose.

--
Gabriel Genellina

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Lie Ryan
On Fri, 12 Dec 2008 09:50:43 -0800, Dennis Lee Bieber wrote:

> On Fri, 12 Dec 2008 03:42:55 -0800 (PST), feb...@gmail.com declaimed the
> following in comp.lang.python:
> 
>> #!/usr/bin/python
>> #Py3k, UTF-8
>> 
>> bank = int(input("How much money is in your account?\n>>")) target =
>> int(input("How much money would you like to earn each year? \n>>"))
>> 
>   Just for my curiosity -- did Python 3.x (besides turning print 
into
> a function) also change input() to behave as the old raw_input()?
> 
>   The above would be very discouraged in Python 2.x... in favor 
of ...
> int(raw_input(...))
> 

Actually, that's the first thing I wanted to bark on, before seeing the 
little note above it: "#Py3k, UTF-8". I wonder though, there is a 
potential problem if someone (users) is running this py3k code in a 
python2.x. The code is a perfectly legal and correct python 2.x code, but 
uses input() instead of raw_input(), we all know the evil of 2.x's input
().

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


Re: Umlauts in idle

2008-12-12 Thread Benjamin Kaplan
On Fri, Dec 12, 2008 at 3:51 PM, a_olme  wrote:

> Hello all,
>
> When I try to use umlauts in idle it will only print out as Unicode
> escape characters. Is it possible to configure idle to print them as
> ordinary characters?


> Best Regards Anders Olme



Make sure you are using Unicode strings and not byte strings. This is why
Python 3 switched to using Unicode by default.

IDLE 2.6.1 on Mac 10.5 :

>>> print u'\u00c4'
Ä
>>> print '\u00c4'
\u00c4


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


Umlauts in idle

2008-12-12 Thread a_olme
Hello all,

When I try to use umlauts in idle it will only print out as Unicode
escape characters. Is it possible to configure idle to print them as
ordinary characters?

Best Regards Anders Olme
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing against different versions of Python

2008-12-12 Thread Benjamin Kaplan
On Fri, Dec 12, 2008 at 2:42 PM, mercado  wrote:

> What is the best way to go about testing against different versions of
> Python?  For example, I have 2.5.2 installed on my machine (Ubuntu Hardy
> 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly
> other versions as well).
>

There are no incompatibilities between 2.5.2 and 2.5.1, unless you were
relying on a bug in your code. AFAIK, the only way to test it against both
would be to compile 2.5.1 yourself. Then, /usr/bin/python would point to
2.5.2 and /usr/local/bin/python would point to python 2.5.1. To test your
script against 2.4, just install the Python2.4 package from apt and invoke
the interpreter with the command python2.4 instead of python. The same thing
goes for python 2.3. Intrepid has a package for Python 3 as well, if you are
willing to do a distro upgrade.



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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Lie Ryan
On Fri, 12 Dec 2008 04:58:36 -0800, feba wrote:

> Actually, I have gedit set to four spaces per tab. I have no reason why
> it's showing up that large on copy/paste, but the file itself is fine.

You've set gedit to _show tabs_ as four spaces, but not to substitute 
tabs with four spaces.

Go to gedit's preference where you change how many spaces is used to 
display tabs, right below it is "Insert spaces instead of tabs".

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


No Scams plz! Read only if you are interested to work from home.

2008-12-12 Thread suppertra...@gmail.com
Lowest air fares, tickets, packages, all inclusive, lower than any
other agencies, we beat other prices:

http://suppertravel.worldventures.com/



Become a travel agent and work from home make , we even pay for
your car payment and mortgage:

http://suppertravel.worldventures.biz/

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


Re: Python is slow

2008-12-12 Thread Bruno Desthuilliers

sturlamolden a écrit :
(snip)


Creating a fast implementation of a dynamic language is almost rocket
science. But it has been done. There is Stronghold, the fastest
version of Smalltalk known to man, on which the Sun Java VM is based.
On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3


cf bearophile's comment on this point (CPU architecture and RAM)


And
most of that magic comes from an implementation of a dynamically typed
language (Smalltalk).


Err... Where is _Java_ "dynamic" actually ? A benchmark of _Smalltalk_ 
VM vs CPython VM would make more sense.



Second, there are other fast implementations of dynamic languages. The
CMUCL and SBCL versions of Common Lisp comes to min; you can see how
SBCL does in the same benchmark (CMUCL tends to be even faster).


Could it be that there are some type hints in the lisp versions of the 
source code ?


So Python is a lot slower than it needs to be. 


Please fix it, you're welcome.
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Bruno Desthuilliers

Tim Rowe a écrit :

2008/12/12 Kirk Strauser :


def get_rate(balance):
   for threshold, rate in ((10, .0173),
   (5, .0149),
   (25000, .0124),
   (1, .0085),
   (0, .006)):
   if balance > threshold:
   return rate
   return .0


Yes, once it's changed from a dictionary to tuples it becomes easier,
doesn't it? D'oh!




A sequence of pairs and a dict are _almost_ interchangeable (mmm... is 
that the correct word ?) representations of a same data set[1] - the 
main difference being ordering. If ordering matters, choose a sequence 
of pairs as main representation - you can easily build a dict from it 
if/when you need it.


[1]
>>> d = dict(a=1, b=2, c=3)
>>> dict(d.items()) == d
True
>>>

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread John Machin
On Dec 13, 6:49 am, "Tim Rowe"  wrote:
> 2008/12/12 John Machin :
>

> > (4) in practice, the "default" action would not be "return 0.0";
> > perhaps something along these lines:
>
> > if balance < -overdraft_limit:
> >   raise Exception(...)
>
> That's more likely to be in the withdrawal routine

You'd certainly hope that this test would appear in the withdrawal
routine.

> (and is probably
> best not handled as an exception, because it's pretty much normal
> flow). If a bank provided a service such as the one implemented by
> this program, there'd be no need for it to know about overdraft limits
> because it's not making actual transactions. Why would they increase
> coupling unneccesarily?

Yeah, you're right, much easier to return 0% interest on a negative
balance [customers happy; no wear and tear on the call centre] and
hope that anomalies are checked somewhere else *and* that somebody #1
is tasked with actioning the anomaly reports and that somebody #2 is
keeping an eye on somebody #1.
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question...

2008-12-12 Thread Tim Rowe
2008/12/12  :

> ah, ok.  now what if I want the variable to be an integer that I
> send?  for instance if I send 99 to the program, it is picking it up
> as a string instead of an integer value.  How do I handle this with
> python??

As 'r' has said, you can cast it to integer. In the real world you'd
want to handle the case where the user passes in something that isn't
an integer, or passes in nothing at all -- it's generally a good idea
to check anything the user enters for validity. It's possibly too
early for you to try to code it, but it's never too early to start
thinking about what you would /want/ it to do. What do you think it
will do for invalid or no command line arguments at the moment? Try
it!

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Kirk Strauser
At 2008-12-12T19:20:52Z, John Machin  writes:

> (1) you meant "if balance > threshold:"

balance >= threshold.  We both mistyped.  :-)

> (2) sequential search can be very fast if the sequence is in
> descending order of probability of occurence ... you might like to
> consider reversing the order

Actually, I just wanted to point out a simplified version of the exact same
algorithm.  Given enough RAM and if the speed was indeed critical, you could
turn that into a tuple of interest rates and jump straight to rate[balance]
in O(1).
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question: if var1 == var2:

2008-12-12 Thread Ethan Furman

Andrew Robert wrote:

Two issues regarding script.

You have a typo on the file you are trying to open.

It is listed with a file extension of .in when it should be .ini .


Pardon?

The OPs original post used .in both in the python code and the command 
line.  Doesn't look like a typo to me.


Out of curiosity, what types of .ini files have one text string per line 
without = ?  The ones I have seen follow this format:


[section name]
setting1 = a value
setting2 = another value

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


Re: Mathematica 7 compares to other languages

2008-12-12 Thread George Neuner
On Mon, 8 Dec 2008 15:14:18 -0800 (PST), Xah Lee 
wrote:

>Dear George Neuner,
>
>Xah Lee wrote:
>> >For example,
>> >the level or power of lang can be roughly order as
>> >this:
>>
>> >assembly langs
>> >C, pascal
>> >C++, java, c#
>> >unix shells
>> >perl, python, ruby, php
>> >lisp
>> >Mathematica
>
>George wrote:
>> According to what "power" estimation?  Assembly, C/C++, C#, Pascal,
>> Java, Python, Ruby and Lisp are all Turing Complete.  I don't know
>> offhand whether Mathematica is also TC, but if it is then it is at
>> most equally powerful.
>
>it's amazing that every tech geekers (aka idiots) want to quote
>“Turing Complete” in every chance. Even a simple cellular automata,
>such as Conway's game of life or rule 110, are complete.
>
>http://en.wikipedia.org/wiki/Conway's_Game_of_Life
>http://en.wikipedia.org/wiki/Rule_110
>
>in fact, according to Stephen Wolfram's controversial thesis by the
>name of “Principle of computational equivalence”, every goddamn thing
>in nature is just about turing complete. (just imagine, when you take
>a piss, the stream of yellow fluid is actually doing turning complete
>computations!)

Wolfram's thesis does not make the case that everything is somehow
doing computation.  

>for a change, it'd be far more interesting and effective knowledge
>showoff to cite langs that are not so-called fuck of the turing
>complete.

We geek idiots cite Turing because it is an important measure of a
language.  There are plenty of languages which are not complete.  That
you completely disregard a fundamental truth of computing is
disturbing.

>the rest of you message went on stupidly on the turing complete point
>of view on language's power, mixed with lisp fanaticism, and personal
>gribes about merits and applicability assembly vs higher level langs.

You don't seem to understand the difference between leverage and power
and that disturbs all the geeks here who do.  We worry that newbies
might actually listen to your ridiculous ramblings and be led away
from the truth.

>It's fine to go on with your gribes, but be careful in using me as a
>stepping stone.

Xah, if I wanted to step on you I would do it with combat boots.  You
should be thankful that you live 3000 miles away and I don't care
enough about your petty name calling to come looking for you.  If you
insult people in person like you do on usenet then I'm amazed that
you've lived this long.

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Tim Rowe
2008/12/12 John Machin :

> (2) sequential search can be very fast if the sequence is in
> descending order of probability of occurence ... you might like to
> consider reversing the order

I find it hard to imagine a bank with so many interest rate thresholds
that the search of the table is likely to be a significant
contribution to the run time!

> (3) for a much longer table, binary search using a function from the
> bisect module could be considered
> (4) in practice, the "default" action would not be "return 0.0";
> perhaps something along these lines:
>
> if balance < -overdraft_limit:
>   raise Exception(...)

That's more likely to be in the withdrawal routine (and is probably
best not handled as an exception, because it's pretty much normal
flow). If a bank provided a service such as the one implemented by
this program, there'd be no need for it to know about overdraft limits
because it's not making actual transactions. Why would they increase
coupling unneccesarily?

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


Testing against different versions of Python

2008-12-12 Thread mercado
What is the best way to go about testing against different versions of
Python?  For example, I have 2.5.2 installed on my machine (Ubuntu Hardy
8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly
other versions as well).

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


Re: newbie question...

2008-12-12 Thread r
i was just giving you an example from my TextEditor.py script.

this is how arg works
lets say you have a script named MyScript.py
---
import sys
print sys.argv
---
call the script with arguments
> MyScript.py 99 100
['C:\\Python25\\MyScript.py', '99', '100']


int(sys.argv[1]) -> 99
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Arnaud Delobelle
alex23  writes:

> Rather than a list comprehension, use a generator expression:
>
> for item in (x for x in sequence if x is not None):
>do_something(x)

I much prefer

for item in sequence:
if x is not None:
do_something(x)

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


Re: var or inout parm?

2008-12-12 Thread Arnaud Delobelle
Marc 'BlackJack' Rintsch  writes:

> On Fri, 12 Dec 2008 07:56:58 -0800, sturlamolden wrote:
>
>> On Dec 12, 4:55 pm, sturlamolden  wrote:
>> 
>>> def __setitem__(self, index, value):
>>>if _buf[index] is not value: # given that _buf is the tuple's
>>> internal buffer
>>>   raise TypeError, 'tuple' object does not support item
>>> assignment
>> 
>> blæh, that should be self._buf[index]
>
> But then the error message is not true anymore because tuples *would* 
> support item assignment when the old and new value are the same.  Which 
> leads to strange things like code that may or may not raise that 
> exception, depending on implementation details:
>
> t = (1, 2)
> t[0] = 1   # Maybe okay -- maybe not.
> t[1] += 0  # Same here.
>
> I'd find that quite odd.
>
> Ciao,
>   Marc 'BlackJack' Rintsch

What I find a bit annoying is when you get both

* an exception
* a mutation

E.g.

>>> t[1] *= 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment

Now is t the same as before?  Sometimes it is:

>>> t
(1, 2)
>>> t[1] *= 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> t
(1, 2)

Sometimes not:

>>> t
(1, [2])
>>> t[1] *= 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> t
(1, [2, 2])

I agree it's not a bug, but I never feel comfortable with it.

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread John Machin
On Dec 13, 5:18 am, Kirk Strauser  wrote:
> At 2008-12-12T18:12:39Z, "Tim Rowe"  writes:
>
>
>
> > Is there a tidy way of making rates and thresholds local to get_rate,
> > without recalculating each time? I suppose going object oriented is
> > the proper way.
>
> > #Py3k,UTF-8
>
> > rates = {0: 0.006, 1: 0.0085, 25000: 0.0124, 5: 0.0149, 10: 
> > 0.0173}
> > thresholds = list(rates.keys())
> > thresholds.sort()
> > thresholds.reverse()
>
> > def get_rate(balance):
> >     for threshold in thresholds:
> >         if balance >= threshold:
> >             return rates[threshold]
> >     else:
> >         return 0.0
>
> How 'bout:
>
> def get_rate(balance):
>     for threshold, rate in ((10, .0173),
>                             (5, .0149),
>                             (25000, .0124),
>                             (1, .0085),
>                             (0, .006)):
>         if balance > threshold:
>             return rate
>     return .0

(1) you meant "if balance > threshold:"
(2) sequential search can be very fast if the sequence is in
descending order of probability of occurence ... you might like to
consider reversing the order
(3) for a much longer table, binary search using a function from the
bisect module could be considered
(4) in practice, the "default" action would not be "return 0.0";
perhaps something along these lines:

if balance < -overdraft_limit:
   raise Exception(...)
return HUGE
--
http://mail.python.org/mailman/listinfo/python-list


Re: [wxpython-users] Dabo 0.9.0 Released

2008-12-12 Thread Peter Decker
On Wed, Dec 10, 2008 at 1:24 PM, Ed Leafe  wrote:
> We are proud (and relieved!) to finally release Dabo 0.9.0, the first
> official release of the framework in six months. We haven't been taking it
> easy during that period; rather, we made some changes that clean up some
> weak spots in the codebase, and as a result can offer a much more solid
> framework, and are on course for a 1.0 release in the near future.

Thanks for all your great work. I've been using Dabo for a couple of
years now, and it just keeps getting better and better!


-- 

# p.d.
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Tim Rowe
2008/12/12 Kirk Strauser :

> def get_rate(balance):
>for threshold, rate in ((10, .0173),
>(5, .0149),
>(25000, .0124),
>(1, .0085),
>(0, .006)):
>if balance > threshold:
>return rate
>return .0

Yes, once it's changed from a dictionary to tuples it becomes easier,
doesn't it? D'oh!

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


Re: Python extension: callbacks blocked when holding button down

2008-12-12 Thread skip

alan> I'm developing a Python extension. It's a wrapper for some
alan> firmware, and simulates the target hardware environment. I'm using
alan> wxPython. I pass a function to the extension so it can let Python
alan> know about certain events.  The code is currently single threaded.

alan> My problem is that the callback seems to have no effect if it is
alan> called while I am holding down a wxButton in the Python GUI. Long
alan> button presses are significant in the firmware so this seems a bit
alan> limiting.

alan> Can anyone explain what is going on? What's the best workaround?

You don't say what platform you're running on, but in many environments,
holding down a menu button "grabs" the window server for the duration of the
button press.  This is certainly the case on Unix running the X Window
System.  In many cases multithreading is the best way around this problem.

-- 
Skip Montanaro - s...@pobox.com - http://smontanaro.dyndns.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question...

2008-12-12 Thread trfilmographer
On Dec 12, 12:59 pm, r  wrote:
> yes, but your script will need to know hoe to handle this.the
> following will open a file who's name was passed to the script
>
> if len(sys.argv) > 1:
>     try:
>         open_file(fname=sys.argv[1])
>     except:
>         pass



ah, ok.  now what if I want the variable to be an integer that I
send?  for instance if I send 99 to the program, it is picking it up
as a string instead of an integer value.  How do I handle this with
python??
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread John Machin
On Dec 13, 4:50 am, Dennis Lee Bieber  wrote:
> On Fri, 12 Dec 2008 03:42:55 -0800 (PST), feb...@gmail.com declaimed the
> following in comp.lang.python:
>
> > #!/usr/bin/python
> > #Py3k, UTF-8
>
> > bank = int(input("How much money is in your account?\n>>"))
> > target = int(input("How much money would you like to earn each year?
> > \n>>"))
>
>         Just for my curiosity -- did Python 3.x (besides turning print into
> a function) also change input() to behave as the old raw_input()?

Yup. There've been some other tectonic plate shift effects, e.g.:

xrange() -> range(); range() -> list(range())
dict.iteritems() -> dict.items(); dict.items() -> list(dict.items())
halfassci() -> repr(); repr() -> ascii()

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Kirk Strauser
At 2008-12-12T18:12:39Z, "Tim Rowe"  writes:

> Is there a tidy way of making rates and thresholds local to get_rate,
> without recalculating each time? I suppose going object oriented is
> the proper way.
>
> #Py3k,UTF-8
>
> rates = {0: 0.006, 1: 0.0085, 25000: 0.0124, 5: 0.0149, 10: 
> 0.0173}
> thresholds = list(rates.keys())
> thresholds.sort()
> thresholds.reverse()
>
> def get_rate(balance):
> for threshold in thresholds:
> if balance >= threshold:
> return rates[threshold]
> else:
> return 0.0

How 'bout:

def get_rate(balance):
for threshold, rate in ((10, .0173),
(5, .0149),
(25000, .0124),
(1, .0085),
(0, .006)):
if balance > threshold:
return rate
return .0
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread MRAB

Tim Rowe wrote:

Since we all seem to be having a go, here's my take. By pulling the
rates and thresholds into a dictionary I feel I'm getting a step
closer to the real world, where these would presumably be pulled in
from a database and the number of interest bands might vary. But is
there a tidier way to get 'thresholds'? I was a bit surprised that
rates.keys() didn't give me a list directly, so although the 3.0
tutorial says "The keys() method of a dictionary object returns a list
of all the keys used in the dictionary, in arbitrary order (if you
want it sorted, just apply the sort() method to )" that's not /quite/
such a given, because "the list of keys" doesn't seem to be there for
the sorting any more.

Is there a tidy way of making rates and thresholds local to get_rate,
without recalculating each time? I suppose going object oriented is
the proper way.

#Py3k,UTF-8

rates = {0: 0.006, 1: 0.0085, 25000: 0.0124, 5: 0.0149, 10: 0.0173}
thresholds = list(rates.keys())
thresholds.sort()
thresholds.reverse()

Why are you putting them into a dict at all? Surely a list of tuples is 
better?


# I could've just written the list in descending order here!
rates = [(0, 0.006), (1, 0.0085), (25000, 0.0124), (5, 0.0149), 
(10, 0.0173)]

thresholds.sort(reversed=True)


def get_rate(balance):
for threshold in thresholds:
if balance >= threshold:
return rates[threshold]
else:
return 0.0



def get_rate(balance):
for threshold, rate in thresholds:
if balance >= threshold:
return rate
return 0.0


balance = int(input("How much money is in your account?\n>>"))
target = int(input("How much money would you like to earn each year?\n>>"))

if balance <= 0:
print("You'll never make your fortune that way!\n")
else:
interest = 0
year = 0
while interest < target:
rate = get_rate(balance)
interest = balance * rate
balance += interest
year += 1
print("Year %s, at %s rate: %s paid, %s in bank." % (year,
rate, interest, balance))


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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Tim Rowe
Since we all seem to be having a go, here's my take. By pulling the
rates and thresholds into a dictionary I feel I'm getting a step
closer to the real world, where these would presumably be pulled in
from a database and the number of interest bands might vary. But is
there a tidier way to get 'thresholds'? I was a bit surprised that
rates.keys() didn't give me a list directly, so although the 3.0
tutorial says "The keys() method of a dictionary object returns a list
of all the keys used in the dictionary, in arbitrary order (if you
want it sorted, just apply the sort() method to )" that's not /quite/
such a given, because "the list of keys" doesn't seem to be there for
the sorting any more.

Is there a tidy way of making rates and thresholds local to get_rate,
without recalculating each time? I suppose going object oriented is
the proper way.

#Py3k,UTF-8

rates = {0: 0.006, 1: 0.0085, 25000: 0.0124, 5: 0.0149, 10: 0.0173}
thresholds = list(rates.keys())
thresholds.sort()
thresholds.reverse()

def get_rate(balance):
for threshold in thresholds:
if balance >= threshold:
return rates[threshold]
else:
return 0.0

balance = int(input("How much money is in your account?\n>>"))
target = int(input("How much money would you like to earn each year?\n>>"))

if balance <= 0:
print("You'll never make your fortune that way!\n")
else:
interest = 0
year = 0
while interest < target:
rate = get_rate(balance)
interest = balance * rate
balance += interest
year += 1
print("Year %s, at %s rate: %s paid, %s in bank." % (year,
rate, interest, balance))


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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Benjamin Kaplan
On Fri, Dec 12, 2008 at 12:50 PM, Dennis Lee Bieber
wrote:

> On Fri, 12 Dec 2008 03:42:55 -0800 (PST), feb...@gmail.com declaimed the
> following in comp.lang.python:
>
> > #!/usr/bin/python
> > #Py3k, UTF-8
> >
> > bank = int(input("How much money is in your account?\n>>"))
> > target = int(input("How much money would you like to earn each year?
> > \n>>"))
> >
>Just for my curiosity -- did Python 3.x (besides turning print into
> a function) also change input() to behave as the old raw_input()?
>

Yes.


>
>The above would be very discouraged in Python 2.x... in favor of ...
> int(raw_input(...))


>
>
> --
>WulfraedDennis Lee Bieber   KD6MOG
>wlfr...@ix.netcom.com   wulfr...@bestiaria.com
>HTTP://wlfraed.home.netcom.com/
>(Bestiaria Support Staff:   web-a...@bestiaria.com)
>HTTP://www.bestiaria.com/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question...

2008-12-12 Thread r
yes, but your script will need to know hoe to handle this.the
following will open a file who's name was passed to the script

if len(sys.argv) > 1:
try:
open_file(fname=sys.argv[1])
except:
pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question...

2008-12-12 Thread Tim Chase

Im new at python and I just want to know if (and how) it is possible
to send parameters to a program.

what I mean is that when we start python I can call a file that should
be run like this: python myfile.py
can I send additional parameters along with it?  like::: python
myfile.py myVar1 myVar2


You're looking for sys.argv:

 t...@rubbish:~$ python - one two
 Python 2.5.2 (r252:60911, May 28 2008, 08:35:32)
[GCC 4.2.4 (Debian 4.2.4-1)] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.

 >>> import sys
 >>> sys.argv
 ['-', 'one', 'two']


-tkc



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


newbie question...

2008-12-12 Thread trfilmographer
Hi!

Im new at python and I just want to know if (and how) it is possible
to send parameters to a program.

what I mean is that when we start python I can call a file that should
be run like this: python myfile.py
can I send additional parameters along with it?  like::: python
myfile.py myVar1 myVar2

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


Re: Python is slow

2008-12-12 Thread Andreas Kostyrka
On Fri, Dec 12, 2008 at 06:17:43AM -0800, sturlamolden wrote:
> None of those projects addresses inefficacies in the CPython
> interpreter, except for psyco - which died of an overdose PyPy.

Bullshit. All that discussion about performance forgets that performance is a 
function of the whole system, not the language.

Worse you can measure it really badly.

E.g. it's relative simple to compare CPython versus IronPython versus Jython. 
For a given benchmark program.

As programs do not trivially translate from language A to language B, nor does 
fluency in language A make you automatically fluent in
language B after learning the syntax.



> 
> PyPy is interesting if they ever will be able to produce something
> useful. They have yet to prove that. Even if PyPy can come up with a
> Python JIT, they will still be decades behind the technologies of
> Strongtalk and Java. That is the problem with reinventing the wheel
> all over again.

Well, it's reinventing the wheel. The problem that Java is a different kind of 
wheel 
(boxed vs. unboxed objects, plus more static compile time bindings), Smalltalk 
is also different (e.g. multiple inheritence),
so you need to have a specific toolbox for the wheel, sorry. Keeping and 
enhancing the tribal wisdom
about toolbox design is what a subtribe of the Computer Scientists do.

Btw, Psyco is not a JIT like most JVMs had them, it's a specializing compiler. 
JVM JITs traditionally speeded up the unboxed data 
type operations. Psyco does something comparable, but it has to specialize 
first on data types. The end effect is similiar, but the 
background of what happens is quite different.

> 
> Not to forget LLVM and Parrot which also will support Python
> frontends.
When they do, they'll do. There have flown quite a bit of Python version since 
the time that it was announced that
Parrot will have a Python frontend.

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


Re: Mathematica 7 compares to other languages

2008-12-12 Thread George Neuner
On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee 
wrote:

>On Dec 10, 2:47 pm, John W Kennedy  wrote:
>> Xah Lee wrote:
>> > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java,
>> > you'll have 50 or hundreds lines.
>>
>> C:
>>
>> #include 
>> #include 
>>
>> void normal(int dim, float* x, float* a) {
>>     float sum = 0.0f;
>>     int i;
>>     float divisor;
>>     for (i = 0; i < dim; ++i) sum += x[i] * x[i];
>>     divisor = sqrt(sum);
>>     for (i = 0; i < dim; ++i) a[i] = x[i]/divisor;
>>
>> }
>
>i don't have experience coding C. 

Then why do you talk about it as if you know something?

>The code above doesn't seems to satisfy the spec.

It does.

>The input should be just a vector, array, list, or
>whatever the lang supports. The output is the same 
>datatype of the same dimension.

C's native arrays are stored contiguously.  Multidimensional arrays
can be accessed as a vector of length (dim1 * dim2 * ... * dimN).

This code handles arrays of any dimensionality.  The poorly named
argument 'dim' specifies the total number of elements in the array.

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


Re: Python is slow

2008-12-12 Thread Luis M . González
On Dec 12, 11:17 am, sturlamolden  wrote:
> On Dec 12, 3:04 pm, Luis M. González  wrote:
>
> > Why don't you guys google a little bit to know what's being done to
> > address python's "slowness"??
>
> Nothing is being done, and woth Py3k it got even worse.
>
> > It has been mentioned in this thread the pypy project (isn't it enough
> > for you??)
> > Other hints: shedskin, psyco, pyrex...
>
> None of those projects addresses inefficacies in the CPython
> interpreter, except for psyco - which died of an overdose PyPy.
>
> PyPy is interesting if they ever will be able to produce something
> useful. They have yet to prove that. Even if PyPy can come up with a
> Python JIT, they will still be decades behind the technologies of
> Strongtalk and Java. That is the problem with reinventing the wheel
> all over again.
>
> Not to forget LLVM and Parrot which also will support Python
> frontends.

So, what's your conclusion?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bidirectional Networking

2008-12-12 Thread Emanuele D'Arrigo
Thank you both for the suggestions! Eventually I tried with threading
as illustrated in the code below.
And it works pretty well! The only problem I'm having with it is that
as the server is a daemon the program should end when the client
thread cease to be alive. But it doesn't seem to work that way and I'm
not sure what's going on! I did achieve my objective though. Two
separate instances of the code below will happily send random numbers
to each other for a few seconds!

Manu

-
To use the following code, cut&paste into two separate *.py files and
invert the port numbers in one file. Then, start them in two separate
shells. WARNING: as mentioned above the two program do not exit and
must be killed, i.e. through the Windows Task Manager or the unix kill
command.
-

import SocketServer
import socket
import threading
import random
from time import sleep

## Network request handler
class MyTCPHandler(SocketServer.StreamRequestHandler):

def handle(self):
self.data = self.rfile.readline().strip()
print "-> RECV: " + self.data + " - Sent by:" +
self.client_address[0]

## Server Thread
class AsyncServer(threading.Thread):
def __init__(self, localServer):
threading.Thread.__init__(self)
self.server = SocketServer.TCPServer(localServer,
MyTCPHandler)
def run(self):
self.server.serve_forever()

## Client Thread
class AsyncClient(threading.Thread):

def __init__(self, remoteServer):
threading.Thread.__init__(self)
self.remoteServer = remoteServer

def run(self):
cycle = 0
while cycle < 1000:

chance = random.random()
if(chance < 0.01):

randomNumber = int(random.random() * 1000)
message = str(randomNumber) + " from remote cycle " +
str(cycle)

try:
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.connect(self.remoteServer)
sock.send(message + "\n")
sock.close()
print("SENT ->: "+str(randomNumber)+ " by local
cycle "+str(cycle))
except:
print("Failed to send number on cycle "+str
(cycle))
pass

cycle += 1

sleep(0.01)

## Simulating local/remote servers with different ports
localServer = ("localhost", )
remoteServer = ("localhost", 1)

asyncServer = AsyncServer(localServer)
asyncServer.daemon = True
asyncServer.start()

asyncClient = AsyncClient(remoteServer)
asyncClient.start()

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


Re: Mathematica 7 compares to other languages

2008-12-12 Thread George Neuner
On Wed, 10 Dec 2008 21:37:34 + (UTC), Kaz Kylheku
 wrote:

>Now try writing a device driver for your wireless LAN adapter in Mathematica.

Notice how Xah chose not to respond to this.

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


Python extension: callbacks blocked when holding button down

2008-12-12 Thread alan . chambers
I'm developing a Python extension. It's a wrapper for some firmware,
and simulates the target hardware environment. I'm using wxPython. I
pass a function to the extension so it can let Python know about
certain events.
The code is currently single threaded.

My problem is that the callback seems to have no effect if it is
called while I am holding down a wxButton in the Python GUI. Long
button presses are significant in the firmware so this seems a bit
limiting.

Can anyone explain what is going on? What's the best workaround?

Thanks.


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


Re: concept of creating structures in python

2008-12-12 Thread Steve Holden
Joe Strout wrote:
> On Dec 12, 2008, at 9:00 AM, Steve Holden wrote:
> 
>>> Change the default value of ds_obj here to None.  Otherwise, you will
>>> certainly confuse yourself (there would be just one default object
>>> shared among all instances).
>>>
>> Joe missed a piece out here. If you change the signature of your
>> D.__init__() to read
>>
>> def  __init__(self, dataName='ND', index = 0, ele_obj=None):
>>
>> then you need to insert the following code at the top of the method:
>>
>>if ele_obj is None:
>>ele_obj = E()
> 
> Yes, if you really need to guarantee that ele_obj is not None, then this
> is the way to do it.
> 
> Of course this would mean that you can't get a None ele_obj even by
> passing it in explicitly as the parameter value -- if you need to
> support that as well, then the solution is a little more complex. 
> Perhaps best in that case would be to just not give ele_obj any default
> value at all, so it becomes a required parameter.
> 
Just for completeness, if you want to be able to pass None then you need
to create a sentinel object, usually just an instantiation of object(),
and test for identity with that to determine that no argument was provided.

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

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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 5:13 pm, Steve Holden  wrote:

> OK, so now you are proposing to alter the parser, and possibly the
> implementation of the INPLACE_ADD opcode in eval.c, so can you give us
> the patch for those, please?

That is not where the problem resides.

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


Re: var or inout parm?

2008-12-12 Thread Steve Holden
sturlamolden wrote:
> On Dec 12, 5:13 pm, Steve Holden  wrote:
> 
>>> It should be the tuple's __setitem__ that was invoked here, not
>>> __iadd__, or the parser is faulty.
>> OK, so now you are proposing to alter the parser, and possibly the
>> implementation of the INPLACE_ADD opcode in eval.c, so can you give us
>> the patch for those, please?
> 
> What? Take a look at the code again:
> 
> mytuple[0] += 1
> 
> should never attempt an __iadd__ on mytuple.
> 
> A sane parser would see this as:
> 
> tmp = mytuple.__getitem__(0)
> tmp = tmp.__iadd__(1)
> mytuple.__setitem__(0, tmp) # should this always raise an exception?
> 
> 
>> Discussion of such behavior as a "bug" is also pejorative, since the
>> current semantics are the way they are by design.
> 
> Right, this bug is by design. You learned that phrase from a guy in
> Redmond?
> 
"It's not a bug, it's a feature" predates Microsoft by several years.

If I say you are ugly, that doesn't make it true. Neither does your
calling this a bug make it a bug.

The fact is that Python doesn't behave the way you want it to. If your
friend doesn't want to do what you do, does that make it a bug in his
behavior. You're being a little juvenile here.

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

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


Re: Removing None objects from a sequence

2008-12-12 Thread Steve Holden
Kirk Strauser wrote:
> At 2008-12-12T15:51:15Z, Marco Mariani  writes:
> 
>> Filip Gruszczyński wrote:
>>
>>> I am not doing it, because I need it. I can as well use "if not elem
>>> is None",
> 
>> I suggest "if elem is not None", which is not quite the same.
> 
> So what's the difference exactly?  "foo is not None" is actually surprising
> to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
> is True.  Why is that?

"is not" is an operator, so the parse is

foo (is not) None

not

foo is (not None)

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

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


Re: newbie question: if var1 == var2:

2008-12-12 Thread MRAB

Kirk Strauser wrote:

At 2008-12-12T15:35:11Z, "J. Cliff Dyer"  writes:


Python has a version equally good:

def chomp(s):
return s.rstrip('\r\n')

You'll hardly miss Perl at all. ;)


I haven't missed Perl in years!  I just wish there was a basestring.stripeol
method because I seem to end up writing the inline version of "chomp" every
time I iterate across a file.

>
Python is open source. You could suggest adding it and/or provide a patch.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread MRAB

Kirk Strauser wrote:

At 2008-12-12T15:51:15Z, Marco Mariani  writes:


Filip Gruszczyński wrote:


I am not doing it, because I need it. I can as well use "if not elem
is None",



I suggest "if elem is not None", which is not quite the same.


So what's the difference exactly?  "foo is not None" is actually surprising
to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
is True.  Why is that?

>
I suppose that it should really be "not is" (cp "not in"), but Guido 
chose to follow the English pattern "is not". "not" returns a Boolean 
(or originally an int) and "is" checks for identity, but the result of 
"is False" or "is True" is down to implementation details in the 
interpreter, so you wouldn't write "is not ..." to mean "is (not ...)" 
anyway, and in practice it's not a problem.

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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 5:13 pm, Steve Holden  wrote:

> > It should be the tuple's __setitem__ that was invoked here, not
> > __iadd__, or the parser is faulty.
>
> OK, so now you are proposing to alter the parser, and possibly the
> implementation of the INPLACE_ADD opcode in eval.c, so can you give us
> the patch for those, please?

What? Take a look at the code again:

mytuple[0] += 1

should never attempt an __iadd__ on mytuple.

A sane parser would see this as:

tmp = mytuple.__getitem__(0)
tmp = tmp.__iadd__(1)
mytuple.__setitem__(0, tmp) # should this always raise an exception?


> Discussion of such behavior as a "bug" is also pejorative, since the
> current semantics are the way they are by design.

Right, this bug is by design. You learned that phrase from a guy in
Redmond?



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


Re: How do I manually uninstall setuptools (installed by egg)?

2008-12-12 Thread Nick Craig-Wood
David Cournapeau  wrote:
>  On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood  
> wrote:
> > David Cournapeau  wrote:
> >>  On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert  wrote:
> >> > On Tue, Dec 9, 2008 at 6:49 PM,   wrote:
> >> >> On Ubuntu, I accidentally manually installed setuptools
> >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file
> >> >> as a shell script via sudo), and now realize I should just be using
> >> >> apt to take care of my system Python packages.
> >> >
> >> > Really, why? setuptools has more Python packages/programs available
> >> > and updates faster than Debian.
> >> > It's also likely that some of the Debian Python packages are installed
> >> > using setuptools anyway.
> >> > So, why do you think apt and not setuptools is The Right Way(tm)?
> >>
> >>  Setuptools is certainly not the right way to install packages
> >>  system-wide on debian, it is very likely to break the whole thing.
> >
> > It wouldn't be too difficult to make a .deb target which would collect
> > all the files that did get installed into a package.  It would be a
> > rather rough and ready package but would do the job.
> 
>  Depends what you mean by would do the job: rather rough certainly does
>  not mean "would do the job" for something as essential as a package
>  IMO.

Essentially a package has files in it in a fixed possition in the
filesystem.  The package manager's (dpkg at this level) job is to keep
track of those file and tell you about conflicts.

You can use alien to turn a tar.gz into a perfectly usable debian
package.  It won't have dependencies, or help or any of the other
things a package needs to be a proper package, but it satisfies my
basic needs that all software is installed as packages, so it can be
uninstalled cleanly.

> > The .deb would then be uninstallable in the usual (dpkg --purge) way.
> >
> > Did anyone think about that?
> 
>  Yes, there is stddeb which does that (make a .deb package from a
>  setuptools package).

Cool, I've not seen that before.  Probably because it isn't in debian!

> > easy_install can do that I think...
> 
>  Not without a lot of hoola, unfortunately; for example, it breaks
>  stow, so I have to use specialy scripts to circumvent the damn thing
>  and make it what I tell him to do. I never understood what's easy
>  about easy install: it is broken in so many ways, and has caused me so
>  many pains - even when I was not using - that I do not trust it at
>  all. I only use it to download packages (and even then it manage to
>  fail more than work), and always install them from setup.py afterwards
>  (at which step I of course also have to circumvent setuptools if the
>  package uses setuptools).

;-)

As a mostly linux developer I always install stuff in packages if
possible.

Failing that I'll use bdist_rpm then alien to convert to a deb which
works well enough I find.

However when I have to make my stuff work on Windows, I find
easy_install to be a fantastic timesaver as compared to looking for
the package on a web site, downloading it, unpacking it installing it
and then repeating for all the dependencies.

easy_install is a long way from being a proper package manager though
:-(

I guess it is aiming at the same territory as the cpan installer with
perl.  My experiences with that is that it works very well, but again
splatters untracked files all over your filesystem.  Debian comes with
dh-make-perl which can use CPAN directly to make .debs which works
quite well.  Something similar based on easy_install for python would
be ideal.  It looks like stdeb could become that one day.

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


Re: var or inout parm?

2008-12-12 Thread Marc 'BlackJack' Rintsch
On Fri, 12 Dec 2008 07:56:58 -0800, sturlamolden wrote:

> On Dec 12, 4:55 pm, sturlamolden  wrote:
> 
>> def __setitem__(self, index, value):
>>if _buf[index] is not value: # given that _buf is the tuple's
>> internal buffer
>>   raise TypeError, 'tuple' object does not support item
>> assignment
> 
> blæh, that should be self._buf[index]

But then the error message is not true anymore because tuples *would* 
support item assignment when the old and new value are the same.  Which 
leads to strange things like code that may or may not raise that 
exception, depending on implementation details:

t = (1, 2)
t[0] = 1   # Maybe okay -- maybe not.
t[1] += 0  # Same here.

I'd find that quite odd.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: Removing None objects from a sequence

2008-12-12 Thread Marco Mariani

Kirk Strauser wrote:


So what's the difference exactly?  "foo is not None" is actually surprising
to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
is True.  Why is that?


Cause I was tired of course, and got the not precedente not right!! Argh
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading online zip files - zipfile and zlib, wbits

2008-12-12 Thread Brendan
On Dec 12, 11:36 am, Brendan  wrote:
> On Dec 12, 10:46 am, Brendan  wrote:
>
>
>
>
>
> > On Dec 12, 10:25 am, Brendan  wrote:
>
> > > I am fooling around with accessing contents of zip files online. I
> > > download the tail end of the zip and use zipfile to get the zip
> > > central directory structure. I download the section of the zip file I
> > > need, directly read the zip file headers and use that information with
> > > zlib to uncompress the data. The files I am examining will always be
> > > compressed using deflate, with a wbits value of -15(minus for
> > > headerless data because I am unsure whether the zip file header is
> > > what zlib expects).
>
> > > I can not find anywhere in the PK Zip Application notes 
> > > (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to
> > > determine the value I should uze for wbits with zlib.decompress. I
> > > have determined it is -15 from experimentation. Does anyone know the
> > > answer to this?
>
> > Okay, I found part of the answer here in the zip app notes
> > [quote]
> > general purpose bit flag: (2 bytes)
>
> >           Bit 0: If set, indicates that the file is encrypted.
>
> >           (For Method 6 - Imploding)
> >           Bit 1: If the compression method used was type 6,
> >                  Imploding, then this bit, if set, indicates
> >                  an 8K sliding dictionary was used.  If clear,
> >                  then a 4K sliding dictionary was used.
> >           Bit 2: If the compression method used was type 6,
> >                  Imploding, then this bit, if set, indicates
> >                  3 Shannon-Fano trees were used to encode the
> >                  sliding dictionary output.  If clear, then 2
> >                  Shannon-Fano trees were used.
>
> >           (For Methods 8 and 9 - Deflating)
> >           Bit 2  Bit 1
> >             0      0    Normal (-en) compression option was used.
> >             0      1    Maximum (-exx/-ex) compression option was
> > used.
> >             1      0    Fast (-ef) compression option was used.
> >             1      1    Super Fast (-es) compression option was used.
> > [/quote]
>
> > Now I just don't understand Why Normal deflate corresponds to 15
> > wbits, and why I have to use headerless for the data, i.e. wbits = -15.
>
> Seems the bit flags are not properly set, bit 2 should be 0 and bit 1
> should be 1, to correspond to maximum compression i.e. wbit = 15.
> Still don't know why wbits has to be negative.- Hide quoted text -
>
> - Show quoted text -

Arg!  Tried a different tack. Took the file header plus compressed
file and concatenated with central directory. Now need only zipfile
module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Kirk Strauser
At 2008-12-12T15:51:15Z, Marco Mariani  writes:

> Filip Gruszczyński wrote:
>
>> I am not doing it, because I need it. I can as well use "if not elem
>> is None",

> I suggest "if elem is not None", which is not quite the same.

So what's the difference exactly?  "foo is not None" is actually surprising
to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
is True.  Why is that?
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Marc 'BlackJack' Rintsch
On Fri, 12 Dec 2008 16:51:15 +0100, Marco Mariani wrote:

> Filip Gruszczyński wrote:
> 
> 
>> I am not doing it, because I need it. I can as well use "if not elem is
>> None",
> 
> I suggest "if elem is not None", which is not quite the same.

In which way is it not the same?  Has the same behavior at least:

In [256]: elem = None

In [257]: not elem is None
Out[257]: False

In [258]: elem is not None
Out[258]: False

In [259]: elem = 42

In [260]: not elem is None
Out[260]: True

In [261]: elem is not None
Out[261]: True

> If you slip such an error in a post, I suggest to practice some time
> writing correct code before having one-liner contests with your
> perl-loving friends :)

If you call something an error, make sure it really is one.  :-)

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


Re: var or inout parm?

2008-12-12 Thread Steve Holden
sturlamolden wrote:
> On Dec 12, 3:54 pm, Steve Holden  wrote:
[...]
>> The interpreter "should not" have a GIL.
> 
>> The tuple "should" check that
>> it is actually being mutated. How?
> 
> In Python it would be something similar to:
> 
> def __setitem__(self, index, value):
>if _buf[index] is not value: # given that _buf is the tuple's
> internal buffer
>   raise TypeError, 'tuple' object does not support item
> assignment
> 
> It should be the tuple's __setitem__ that was invoked here, not
> __iadd__, or the parser is faulty.
> 
OK, so now you are proposing to alter the parser, and possibly the
implementation of the INPLACE_ADD opcode in eval.c, so can you give us
the patch for those, please?

This is exactly the point I was trying to make. It's easy to stand on
the sidelines and make sensible- or even intelligent-sounding
suggestions about how to change Python. But inside the interpreter
there's a maze of twisty little passages all alike (or similar
complexity), and hand-waving doesn't get you anywhere.

Discussion of such behavior as a "bug" is also pejorative, since the
current semantics are the way they are by design. You are therefore
disagreeing with the design of Python rather than discussing a bug in
its implementation.

That also raises the issues of how you get Jython and IronPython to
implement the same semantics, and whether you care about the millions of
lines of code that already assumes the current behavior.

You've got a lot of work to do ...

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

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


Re: concept of creating structures in python

2008-12-12 Thread Joe Strout

On Dec 12, 2008, at 9:00 AM, Steve Holden wrote:


Change the default value of ds_obj here to None.  Otherwise, you will
certainly confuse yourself (there would be just one default object
shared among all instances).


Joe missed a piece out here. If you change the signature of your
D.__init__() to read

def  __init__(self, dataName='ND', index = 0, ele_obj=None):

then you need to insert the following code at the top of the method:

   if ele_obj is None:
   ele_obj = E()


Yes, if you really need to guarantee that ele_obj is not None, then  
this is the way to do it.


Of course this would mean that you can't get a None ele_obj even by  
passing it in explicitly as the parameter value -- if you need to  
support that as well, then the solution is a little more complex.   
Perhaps best in that case would be to just not give ele_obj any  
default value at all, so it becomes a required parameter.


Best,
- Joe

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


Re: newbie question: if var1 == var2:

2008-12-12 Thread Kirk Strauser
At 2008-12-12T15:35:11Z, "J. Cliff Dyer"  writes:

> Python has a version equally good:
>
> def chomp(s):
> return s.rstrip('\r\n')
>
> You'll hardly miss Perl at all. ;)

I haven't missed Perl in years!  I just wish there was a basestring.stripeol
method because I seem to end up writing the inline version of "chomp" every
time I iterate across a file.
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: concept of creating structures in python

2008-12-12 Thread Steve Holden
Joe Strout wrote:
> On Dec 11, 2008, at 10:52 PM, navneet khanna wrote:
> 
>> I want to create a structure within a structure i.e. nested structures
>> in python.
>> I tried with everything but its not working.
>> my code is like this:
>>
>> class L(Structure):
>>
>> def __init__(self,Name='ND',Addr=0,ds_obj = D()):
> 
> Change the default value of ds_obj here to None.  Otherwise, you will
> certainly confuse yourself (there would be just one default object
> shared among all instances).
> 
>> self.Name = Name
>> self.Addr = Addr
>> self.ds_obj = ds_obj
>>
>>
>> class D(Structure):
>>
>> def  __init__(self,dataName='ND',index = 0,ele_obj=E()):
>>
>> self.dataName = dataName
>> self.index = index
>> self.ele_obj = ele_obj
> 
> Same thing here with ele_obj -- have it default to None to save yourself
> grief.
> 
> Otherwise, these look fine.
> 
Joe missed a piece out here. If you change the signature of your
D.__init__() to read

 def  __init__(self, dataName='ND', index = 0, ele_obj=None):

then you need to insert the following code at the top of the method:

if ele_obj is None:
ele_obj = E()

[You'll note, by the way, I have inserted standard spacing into the
"def" statement to enhance readbility: you should use spaces after all
commas if you want your code to be easy for other programmers to read).
This avoids a common beginner pitfall. Your original code would create a
single E object that would be used as the defauilt for all Ds created
without explicitly passing an ele_obj. Then if that object were changed
(mutated) in some way, all such E's would see a change had been made to
their ele_obj. With the extra code, a different ele_obj is created for
each E that isn't passed one.

The same argument applies to L.__init__()'s ds_obj argument.
> 
>> these are two structures. I want to refer D structure in L one and use
>> it. I want to access the value of D structure like L.D.index = 0.
> 
[...]

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

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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 4:55 pm, sturlamolden  wrote:

> def __setitem__(self, index, value):
>if _buf[index] is not value: # given that _buf is the tuple's
> internal buffer
>   raise TypeError, 'tuple' object does not support item
> assignment

blæh, that should be self._buf[index]




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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 3:54 pm, Steve Holden  wrote:
> sturlamolden wrote:
> > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch  wrote:
>
> >> No bug because a mutation *is* attempted.  ``a += x`` calls `a.__iadd__`
> >> which *always* returns the result which is *always* rebound to the name
> >> `a`.  Even with mutable objects where `__iadd__()` simply returns
> >> `self`!
>
> > No, a mutation is not attempted, even if __iadd__() always returns a
> > value. If a rebinding of a member to the same member is attempted, the
> > tuple should not raise an exception. The tuple should check that it is
> > actually being *mutated* before it raises any exception. There is an
> > attempted write to the tuple, but not an attempted mutation of the
> > tuple. The tuple should tell the difference. Immutability does not
> > imply inwriteability, if the write operation changes nothing. But the
> > tuple raises an exception on any write attempt.
>
> OK, so if you regard the current behavior as a bug explain how to modify
> the tuple's __iadd__ method and the coding of the INPLACE_ADD operator.
> At least in pseudocode.
>
> Criticism is easy. Now demonstrate that it's *informed* criticism.
> Enough of the "should". I am always suspicious of suggestions that say
> what the interpreter "should" or "should not" do. It makes it sound as
> though you can wave a magic wand to achieve the desired behavior.


> The interpreter "should not" have a GIL.

> The tuple "should" check that
> it is actually being mutated. How?

In Python it would be something similar to:

def __setitem__(self, index, value):
   if _buf[index] is not value: # given that _buf is the tuple's
internal buffer
  raise TypeError, 'tuple' object does not support item
assignment

It should be the tuple's __setitem__ that was invoked here, not
__iadd__, or the parser is faulty.


S.M.



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


Re: Python is slow

2008-12-12 Thread Christian Heimes
sturlamolden schrieb:
> On Dec 12, 3:04 pm, Luis M. González  wrote:
> 
>> Why don't you guys google a little bit to know what's being done to
>> address python's "slowness"??
> 
> Nothing is being done, and woth Py3k it got even worse.

Indeed, it *is* slower for now. As I already said in another thread our
top priorities were feature completeness and bug fixing. Optimizations
will follow the features in the near future.

Christian

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


Re: Removing None objects from a sequence

2008-12-12 Thread Marco Mariani

Filip Gruszczyński wrote:



I am not doing it, because I need it. I can as well use "if not elem
is None",


I suggest "if elem is not None", which is not quite the same.

If you slip such an error in a post, I suggest to practice some time 
writing correct code before having one-liner contests with your 
perl-loving friends :)


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


Re: Mathematica 7 compares to other languages

2008-12-12 Thread Tom McGlynn
On Dec 11, 6:46 am, "William James"  wrote:
> John W Kennedy wrote:
> > Xah Lee wrote:
> > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or
> > > Java, you'll have 50 or hundreds lines.
>
> > Java:
>
> > static float[] normal(final float[] x) {
> >float sum = 0.0f;
> >for (int i = 0; i < x.length; ++i) sum += x[i] * x[i];
> >final float divisor = (float) Math.sqrt(sum);
> >float[] a = new float[x.length];
> >for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor;
> >return a;
> > }

Calculating the norm of a vector is a numeric operation, so not
surprising it's pretty
easy to do in Fortran.  While pre Fortran 90 would using something
similar to the above,
today you can do it as

norm = x/sqrt(sum(x*x))

for an arbitratry vector (or tensor for that matter).  It would take a
couple more lines to wrap it up in a function

real function norm(x)
real x(*)
norm = x/sqrt(sum(x*x))
end

[Caveat: my Fortran is more than rusty ]

So even Fortran can do this in only 1 line or 4 as a function.

Judging by the LOC and, at least to my eye, the clarity of the method,
Fortran is a real winner!  Just to give a tiny bit of Java relevance
to the discussion: It's the ability to write functions that
straightforwardly express the mathematical intent of the user that
makes operator overloading (in this case over arrays) so useful in
many numerical contexts.  This is cross-posted to Python as well.  I
understand it has similar array arithmetic capabilities to Fortran. I
believe this may be one reason for Python's burgeoning popularity

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


Re: Reading online zip files - zipfile and zlib, wbits

2008-12-12 Thread Brendan
On Dec 12, 10:46 am, Brendan  wrote:
> On Dec 12, 10:25 am, Brendan  wrote:
>
> > I am fooling around with accessing contents of zip files online. I
> > download the tail end of the zip and use zipfile to get the zip
> > central directory structure. I download the section of the zip file I
> > need, directly read the zip file headers and use that information with
> > zlib to uncompress the data. The files I am examining will always be
> > compressed using deflate, with a wbits value of -15(minus for
> > headerless data because I am unsure whether the zip file header is
> > what zlib expects).
>
> > I can not find anywhere in the PK Zip Application notes 
> > (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to
> > determine the value I should uze for wbits with zlib.decompress. I
> > have determined it is -15 from experimentation. Does anyone know the
> > answer to this?
>
> Okay, I found part of the answer here in the zip app notes
> [quote]
> general purpose bit flag: (2 bytes)
>
>           Bit 0: If set, indicates that the file is encrypted.
>
>           (For Method 6 - Imploding)
>           Bit 1: If the compression method used was type 6,
>                  Imploding, then this bit, if set, indicates
>                  an 8K sliding dictionary was used.  If clear,
>                  then a 4K sliding dictionary was used.
>           Bit 2: If the compression method used was type 6,
>                  Imploding, then this bit, if set, indicates
>                  3 Shannon-Fano trees were used to encode the
>                  sliding dictionary output.  If clear, then 2
>                  Shannon-Fano trees were used.
>
>           (For Methods 8 and 9 - Deflating)
>           Bit 2  Bit 1
>             0      0    Normal (-en) compression option was used.
>             0      1    Maximum (-exx/-ex) compression option was
> used.
>             1      0    Fast (-ef) compression option was used.
>             1      1    Super Fast (-es) compression option was used.
> [/quote]
>
> Now I just don't understand Why Normal deflate corresponds to 15
> wbits, and why I have to use headerless for the data, i.e. wbits = -15.

Seems the bit flags are not properly set, bit 2 should be 0 and bit 1
should be 1, to correspond to maximum compression i.e. wbit = 15.
Still don't know why wbits has to be negative.
--
http://mail.python.org/mailman/listinfo/python-list


Re: concept of creating structures in python

2008-12-12 Thread Joe Strout

On Dec 11, 2008, at 10:52 PM, navneet khanna wrote:

I want to create a structure within a structure i.e. nested  
structures in python.

I tried with everything but its not working.
my code is like this:

class L(Structure):

def __init__(self,Name='ND',Addr=0,ds_obj = D()):


Change the default value of ds_obj here to None.  Otherwise, you will  
certainly confuse yourself (there would be just one default object  
shared among all instances).



self.Name = Name
self.Addr = Addr
self.ds_obj = ds_obj


class D(Structure):

def  __init__(self,dataName='ND',index = 0,ele_obj=E()):

self.dataName = dataName
self.index = index
self.ele_obj = ele_obj


Same thing here with ele_obj -- have it default to None to save  
yourself grief.


Otherwise, these look fine.


these are two structures. I want to refer D structure in L one and  
use it. I want to access the value of D structure like L.D.index = 0.


But you didn't name it "D" -- if you have an L object, say "foo", then  
you'd get to it's D object as foo.ds_obj (since that's what you named  
it in L.__init__).  If you then wanted to get to that thing's E  
object, it'd be foo.ds_obj.ele_obj.


Best,
- Joe

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


Re: newbie question: if var1 == var2:

2008-12-12 Thread J. Cliff Dyer

On Thu, 2008-12-11 at 13:44 -0600, Kirk Strauser wrote:
> At 2008-12-11T17:24:44Z, rdmur...@bitdance.com writes:
> 
> > >>> '  ab c  \r\n'.rstrip('\r\n')
> > '  ab c  '
> > >>> '  ab c  \n'.rstrip('\r\n')
> > '  ab c  '
> > >>> '  ab c  '.rstrip('\r\n')
> > '  ab c  '
> 
> I didn't say it couldn't be done.  I just like the Perl version better.

Python has a version equally good:

def chomp(s):
return s.rstrip('\r\n')

chomp("foo\n")
chomp("foo")
chomp("perl\r\n")

You'll hardly miss Perl at all. ;)

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


Re: Removing None objects from a sequence

2008-12-12 Thread Vito De Tullio
Filip Gruszczyński wrote:

> I checked itertools, but the only thing that
> seemed ok, was ifilter - this requires seperate function though, so
> doesn't seem too short. 

is this too much long?

>>> from itertools import ifilter
>>> for element in ifilter(lambda x: x is not None, [0,1,2,None,3,None,4]):
... print element
...
0
1
2
3
4
>>>   

-- 
By ZeD

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


  1   2   >