Re: why in returns values for array and keys for dictionary

2008-08-26 Thread Asun Friere
On Aug 26, 10:49 am, ++imanshu [EMAIL PROTECTED] wrote:
 Hi,

 Wouldn't it be nicer to have 'in' return values (or keys) for both
 arrays and dictionaries.


NO!

When you iterate over a list (or even a array) it is the members of
the list in the order they appear that is of interest.  When you
iterate over a dictionary it is the relationship between the (unique)
key and the (possibly non-unique) value that is of interest.  Moreover
the sequence of values in a dictionary lacks meaning.

What is the 'key' of a list?  It's index?  It would be cumbersome to
iterate over the range(len(list)) and then have to use the index
values to pull out the values from that list.  On the otherhand it
would be useless for 'in' (in the sense of for x in {...}) to return a
series of unordered values, with no way to get at the key, rather than
keys (from which the values are directly accessible).

And what would you like file_like objects, for example, to return?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalents of Ruby's ! methods?

2008-08-26 Thread mumbler
On Aug 26, 9:47 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Mon, 25 Aug 2008 17:04:07 +, Grzegorz Staniak wrote:
  On 25.08.2008, Terry Reedy [EMAIL PROTECTED] wroted:

  The newish sorted() and reversed() built-ins were meant to complement
  list.sort and list.reverse, not replace them.

  BTW, is there a reason why sorted() on a list returns a list, while
  reversed() on the same list returns an iterator?

 Until the day that somebody discovers how to sort a list without seeing
 all the items first, there's no point in sorted() returning an iterator.

To nitpick, this is not strictly true: sure, you're at best O(nlogn)
on sorting the entire list, but you could return the first element of
the 'sorted' list in O(n) (if you don't mind using a O(n^2) algorithm
for the whole sort). i.e. if you have a use case where you're only
likely to look at the first few elements of a sorted list, it would
make some sense to have an iterator.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with extension modules built in debug mode

2008-08-26 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


I've come to the conclusion that posting about Embedded Python on the
Python forums is a complete waste of time.  I hope I can get some
useful insights here.


(just curious, but what are the Python forums?  isn't the 
newsgroup/mailing list *the* Python forum?)


/F

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


Non-evil multithreaded WSGI server?

2008-08-26 Thread Gerhard Häring

In a recent experiment I've done this:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from wsgiref.simple_server import make_server, demo_app
from SocketServer import ThreadingMixIn

# Let's make a WSGI server that can use multiple threads.

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
Handle requests in a separate thread.

# Evil! ;-)
from wsgiref.simple_server import WSGIServer as MyWSGIServer
MyWSGIServer.__bases__ = (ThreadedHTTPServer,)

Now I wonder if there's a less evil way that does not involve copy  
paste of the WSGIServer code (only couple of lines, but I hate 
duplication)?!


-- Gerhard

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


Re: rspec for python

2008-08-26 Thread Rustom Mody
 Gerhard Haring wrote:


 Have you actually used this rspec thing in Ruby? I always wonder with
 such things.

 Same with all the other hyped technologies of yesteryear. Anybody out
 there who really uses model-driven development?
  -- Gerhard


Two laws are (the) most fundamental in our field.

1. The Church-Turing thesis says that all computable systems (aka prog
languages and their spinoffs) are equivalent

2. Wittgenstein's The limits of my language are the limits of my world
says that significant differences in computing power are (ultimately)
differences in language.

Hence what a language can (and cannot) do are always of deep interest.

Specifically: whether rpsec works -- I dont know -- Ive not used it.
There are attempts in the python world: specipy and pyspec but they dont
seem mature yet.

I am also interested in what Joh says


 Compare Rake and Scons - the Ruby and Python embedded DSL build systems
 that are
 intended to replace Make, Ant and similar external build DSLs. You can
 see the difference in fluency.



What is the difference? And how much is due to the relatively greater
maturity of rake and how much due to the intrinsic differences of python and
ruby? Anyhow which due you prefer?
--
http://mail.python.org/mailman/listinfo/python-list

Re: python xslt library

2008-08-26 Thread Stefan Behnel
Owen Zhang wrote:
 Can anyone recommand the best performance python xslt library?

lxml. It's based on libxml2/libxslt.

http://codespeak.net/lxml

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


Re: File copying from a menu

2008-08-26 Thread Fredrik Lundh

Brandon wrote:

I'm attempting to have a file copied from a menu selection.  The menu 
already exists, but it won't even create the menu item.  If anyone has any 
ideas, please let me know. 


try cutting down your code to a minimal example that illustrates the 
problem, and post that code (that'll also allow us to figure out what 
library you're using to create the menu...).


/F

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


mailbox module

2008-08-26 Thread ra9ftm
Hi all. I am trying to use mailbox module, mbox class like this:

import mailbox
m1 = mailbox.mbox('./ra9ftm2')

But it gives the following:

ra9ftm:/home/ra9ftm/pyemail# python mbox1.py
Traceback (most recent call last):
  File mbox1.py, line 2, in ?
m1 = mailbox.mbox('./ra9ftm2')
AttributeError: 'module' object has no attribute 'mbox'
ra9ftm:/home/ra9ftm/pyemail#


What's wrong?
I am using Debian 4.0 Etch for my tests. May be old version of python
in this repository?

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


Re: why in returns values for array and keys for dictionary

2008-08-26 Thread Erik Max Francis

Marc 'BlackJack' Rintsch wrote:


On Mon, 25 Aug 2008 19:57:06 -0700, alex23 wrote:


On Aug 26, 10:49 am, ++imanshu [EMAIL PROTECTED] wrote:

Wouldn't it be nicer to have 'in' return values (or keys) for
both
arrays and dictionaries. Arrays and Dictionaries looked so similar in
Python until I learned this difference.

[…]

In both cases, 'in' returns a boolean indicating the existence of an
item in the list, or a key in the dict. I'm not sure why you'd need it
to return the item you're checking for the existence of, as you'd have
to have that item before you could do the check.

Have I missed what you're asking for here? Could you provide a
pseudocode example to demonstrate what you mean?


The OP isn't talking about the ``in`` operator but ``in`` as part of 
``for … in …``.  So it's actually the question why ``list(a_dict)`` 
doesn't return a list of values but a list of keys.


That is basically the same question.  Iterating over a list gives you 
its elements, and using the `in` operator with lists tells you whether 
or not an object is an element of the list.  Iterating over a dictionary 
gives you its _keys_, not its values, and the `in` operator with 
dictionaries tells you whether or not a _key_ is in the dictionary.


 l = [1, 2, 3]
 for x in l: print x
...
1
2
3
 0 in l
False
 1 in l
True
 d = {'a': 1, 'b': 2, 'c': 3}
 for x in d: print x
...
a
c
b
 'a' in d
True
 1 in d
False

The reason why people find it more useful to deal with keys rather than 
values of a dictionary during iteration or containment testing is ... 
because that tends to be what you're usually more interested in, and is 
more efficient.  For another thing, if you're doing a lot of testing for 
containment in values, then it's likely you're not using the right data 
structure, or combination of data structures.  That's not what 
dictionaries are for.


--
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
 San Jose, CA, USA  37 18 N 121 57 W  AIM, Y!M erikmaxfrancis
  Well I have been puppetized / Oh how I have compromised
   -- Lamya
--
http://mail.python.org/mailman/listinfo/python-list

Re: why in returns values for array and keys for dictionary

2008-08-26 Thread Erik Max Francis

++imanshu wrote:


Wouldn't it be nicer to have 'in' return values (or keys) for both
arrays and dictionaries. Arrays and Dictionaries looked so similar in
Python until I learned this difference.


It's because dealing with keys makes far more sense, since that's how 
the dictionary data structure works.  If you're doing this an awful lot 
-- whether testing for inclusion or iterating -- then you're probably 
using the wrong data structure.


--
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
 San Jose, CA, USA  37 18 N 121 57 W  AIM, Y!M erikmaxfrancis
  Well I have been puppetized / Oh how I have compromised
   -- Lamya
--
http://mail.python.org/mailman/listinfo/python-list


Re: Micro-threading PEP proposal announcement

2008-08-26 Thread Pau Freixes
Sorry Bruce,

When can I read this PEP ? I'm interesting

Bye

On Mon, Aug 25, 2008 at 7:15 PM, Bruce Frederiksen [EMAIL PROTECTED]wrote:

 I wanted to make everybody aware that I've posted a (rather long and
 involved) PEP proposal for adding micro-threading to Python on
 python-ideas for feedback and review.

 In a nutshell, this proposal implements the Twisted Deferred/Reactor at
 the C level so that the Python programmer gets the advantages that Twisted
 offers without having to write their code in an event driven style.  Thus,
 legacy Python code not written in the Twisted style (Django, TurboGears,
 WSGI apps) will gain the benefits of Twisted with almost no additional
 work.

 This PEP provides similar benefits to GUI toolkits where, again, Python
 programmers have been faced with event driven programming.  So using this
 PEP, GUI toolkits could hide this event driven programming from the Python
 programmer, making GUI programming much easier.  For example, you would no
 longer have to use a modal dialog just to make the programming easier.

 The C-level Deferreds and Reactor are not made visible to the Python
 programmer (as they are in Twisted).

 Rather, what is visible is a very simple micro-thread that allows for
 start_and_forget threads, parallel threads (where you're only
 interested in the final return value) and fully cooperative threads
 communicating over micro-pipes (which, BTW, gives us a new way to write
 generators that allows one generator to simply call another one to have
 the second generator's output included with its own output without having
 to capture and pass back values).

 As there is a great deal of traffic on comp.lang.python, I don't expect to
 be able to keep up with the posts here and would prefer to discuss this
 on python-ideas...

 If there is any interest in this, please let me know!  If I don't see any
 interest, I'll assume that it's not solving a real problem and will let it
 quietly die on the vine...

 Thank you for your attention!

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




-- 
Pau Freixes
Linux GNU/User
--
http://mail.python.org/mailman/listinfo/python-list

Re: mailbox module

2008-08-26 Thread ra9ftm
ok, may be it is truth, because class UnixMailbox is working. I found
it in Depricated classess and methods in manual :(

here is only version 2.4 in Debian


ra9ftm:

 I am using Debian 4.0 Etch for my tests. May be old version of python
 in this repository?
--
http://mail.python.org/mailman/listinfo/python-list


How to manipulate list of dictionary

2008-08-26 Thread ajak_yahoo
Hi,

Need some help, I have a list of dictionary as below,

table = [{Part #:Washer,Po #:AE00128,qty:100},
 {Part #:Brake Pad,Po #:AE00154,qty:150},
 {Part #:Mesh,Po #:AE00025,qty:320},
 {Part #:Mouse,Po #:AE00207,qty:120},
 {Part #:Insulator,Po #:AE0013,qty:190}]

How to manipulate the table?

I need to search for the Po #, and display the result as below.


Part # : Mouse
Po #   : AE00207
Qty: 120 pcs



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

Re: smart quotes

2008-08-26 Thread Peter Otten
Adrian Smith wrote:

 Can anyone tell me how to get rid of smart quotes in html using
 Python? I've tried variations on
 stuff = string.replace(stuff, \“, \), but to no avail, presumably
 because they're not standard ASCII.

Convert the string to unicode. For that you have to know its encoding. I
assume UTF-8:

 s = a “smart quote” example
 u = s.decode(utf-8)

Now you can replace the quotes (I looked up the codes in wikipedia):

 u.replace(u\u201c, ).replace(u\u201d, )
u'a smart quote example'

Alternatively, if you have many characters to remove translate() is more
efficient:

 u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019]))
u'a smart quote example'

If necessary convert the result back to the original encoding:

 clean = u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019]))
 clean.encode(utf-8)
'a smart quote example'

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

Are dictionaries the same as hashtables?

2008-08-26 Thread cnb
Are dictionaries the same as hashtables?
--
http://mail.python.org/mailman/listinfo/python-list


How to bind an event in Tix combo box?

2008-08-26 Thread dudeja . rajat
Hi,

I'm a newbie and created a new combo box with Tix.
The combo box is filled with the required items.

I've used Tkinter's listbox and used the ListboxSelect event and
bind that with a callback.
Now, I want to do the same stuff with the Tix combo box.

Please suggest how can I do the same in Tix combo box.

Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Martin Marcher
On 2008-08-26 00:32:20, cnb wrote:
 Are dictionaries the same as hashtables?

Yes, but there is nothing in there that does sane collision handling
like making a list instead of simply overwriting.

PS: your sig was *a bit* longer than you question. please don't do
that...


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Are dictionaries the same as hashtables?

2008-08-26 Thread cnb
On Aug 26, 9:43 am, Martin Marcher [EMAIL PROTECTED] wrote:
 On 2008-08-26 00:32:20, cnb wrote:

  Are dictionaries the same as hashtables?

 Yes, but there is nothing in there that does sane collision handling
 like making a list instead of simply overwriting.

 PS: your sig was *a bit* longer than you question. please don't do
 that...

  signature.asc
  1KViewDownload

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


Re: extract text from ods TableCell using odfpy

2008-08-26 Thread frankentux
Ok. Sorted it out, but only after taking a round trip over
xml.minidom. Here's the working code:

#!/usr/bin/python
from odf.opendocument import Spreadsheet
from odf.opendocument import load
from odf.table import TableRow,TableCell
from odf.text import P
doc = load(/tmp/match_data.ods)
d = doc.spreadsheet
rows = d.getElementsByType(TableRow)
for row in rows[:2]:
cells = row.getElementsByType(TableCell)
for cell in cells:
tps = cell.getElementsByType(P)
if len(tps)  0:
for x in tps:
print x.firstChild
--
http://mail.python.org/mailman/listinfo/python-list


ctypes - loading 'librsvg-2-2.dll'

2008-08-26 Thread Tim Grove

Any ideas why a particular dll won't load on Windows XP Pro using

ctypes? The dll in question is 'librsvg-2-2.dll' (a link if anyone cares to try!!! 
http://ftp.gnome.org/pub/gnome/binaries/win32/librsvg/2.22/) The other dlls from the GTK libraries seem to load okay, 
so I'm more than puzzled!! I get the following results (whichever class 
I use):


l=CDLL(r'D:\SILSign\librsvg-2-2.dll')
Traceback (most recent call last):
 File input, line 1, in module
 File C:\PYTHON25\LIB\ctypes\__init__.py, line 349, in __init__
   self._handle = _dlopen(self._name, mode)
WindowsError: [Error 127] The specified procedure could not be found

Best regards,
Tim


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


Re: How to manipulate list of dictionary

2008-08-26 Thread Simon Brunning
2008/8/26 ajak_yahoo [EMAIL PROTECTED]:
 Need some help, I have a list of dictionary as below,

 table = [{Part #:Washer,Po #:AE00128,qty:100},
  {Part #:Brake Pad,Po #:AE00154,qty:150},
  {Part #:Mesh,Po #:AE00025,qty:320},
  {Part #:Mouse,Po #:AE00207,qty:120},
  {Part #:Insulator,Po #:AE0013,qty:190}]

 How to manipulate the table?

 I need to search for the Po #, and display the result as below.


 Part # : Mouse
 Po #   : AE00207
 Qty: 120 pcs

Well, that's a really bad data structure for what you want to do, but
you can do it with something like (untested):

wanted = 'AE00207'

for part in table:
if part['Po #'] == wanted:
print Part #:\t%(Part #)s\nPo #:\t%(Po #)s\nQty #:\t%(qty)s % part

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: property() usage - is this as good as it gets?

2008-08-26 Thread Bruno Desthuilliers

David Moss a écrit :

Hi,

I want to manage and control access to several important attributes in
a class and override the behaviour of some of them in various
subclasses.

Below is a stripped version of how I've implemented this in my current
bit of work.

It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).

Is this as good as it gets or can this be refined and improved
especially if I was to add in a couple more attributes some fairly
complex over-ride logic?


(snip code)


Remember that properties have nothing magical - they're just one 
possible (and very handy) way to use the descriptor protocol to 
implement computed attributes. If you have to resort to any non-obvious 
trick or just too much boilerplate code with properties, then it's 
probably time to implementent your own custom descriptor object.

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


Re: rules of thumb for cross os code

2008-08-26 Thread Bruno Desthuilliers

DwBear75 a écrit :

I am considering using python as a replacement for a lot of bash
scripting that I have been doing. I would like to be as cross platform
as possible, writing scripts for both windows and linux. Are there any
guides are general rules of thumb on
1) keeping code os independant


obvious
Use os.path, avoid any os-specific module.
/obvious


2) nifty lambda's or other things to create functions fit for the
environment


You don't need lambdas here.

import random
some_condition = random.choice((True, False))

if some_condition:
def myfunc():
print myfunc for 'somecondition==True'
else:
def myfunc():
print myfunc for 'somecondition==False'




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


Retrieve Win32 domain name

2008-08-26 Thread Salim Fadhley
I'm looking for a method to retrieve a Windows Domain name (not a DNS
Domain name).

I know this can be done by simply reading an environment variable,
however on the machines I need to work with sometimes the environment
variables can be messed-up and are not trustworthy.

Is there somebody who knows the Win32 library who can point me to the
function I need? The Win32Net seems to contain a whole load of
functions for manipulating Windows networking resources, however I
couldn't find a function which simply returned information about the
local computer.

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


Retrieve Win32 domain name

2008-08-26 Thread Salim Fadhley
I'm looking for a method to retrieve a Windows Domain name (not a DNS
Domain name).

I know this can be done by simply reading an environment variable,
however on the machines I need to work with sometimes the environment
variables can be messed-up and are not trustworthy.

Is there somebody who knows the Win32 library who can point me to the
function I need? The Win32Net seems to contain a whole load of
functions for manipulating Windows networking resources, however I
couldn't find a function which simply returned information about the
local computer.

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


Re: Python String Immutability Broken!

2008-08-26 Thread Hendrik van Rooyen

Simon Brunning:

You can indeed use ctypes to modify the value of a string - see
http://tinyurl.com/5hcnwl. You can use it to crash the OS, too.

My advice - don't.

Thanks for the link.

Any advice on what to do or use as an I/O structure for dissemination?


Ken Seehart:

8--- using ctypes to make 1+14 = 10  --

I love ctypes.  So cool.  It's not supposed to be safe.

And here I thought I was weird…

Life is either a daring adventure or nothing. Security does not
exist in nature, nor do the children of men as a whole experience
it. Avoiding danger is no safer in the long run than exposure.
*Helen Keller http://www.quotationspage.com/quotes/Helen_Keller/*
/US blind  deaf educator (1880 - 1968)/

Of course I would not hire anyone who believes this quote, other than
Helen Keller, if she were still with us.

Why not? – as I see it, the Keller quote states the literal truth of
the matter – we all live under an illusion of security – but then
that might just be because I am South African, and the country is
run by cattle thieves.

It is quite possible to write a small program that works using abused
strings.  But my life better not depend on it.  Among other things, if
you use the abused string as a key anywhere, you will not get correct
results.  Trying to change the length of the string will cause
disasters.  Lengthening a string will corrupt memory, and shortening the
string will not shorten it but rather embed '\0' in it.

Understood. – remember I am using it as a kind of array of “pseudoports”
- memory representations of what goes on on wires on the outside.

So only a real madman would try to impute the kind of cross bit
correlation needed to use the bunch of bits as a key. The length would
be fixed, governed by the existence of real hardware on the outside.

Ken Seehart again:

Yes, there is a better way. Use a character array instead of a string.

The original reason I used a string directly instead of array.array was
to try to skip the serialisation step when disseminating the information
via sockets.

As you can appreciate, this is all “hot stuff” as it represents said
wire states, and is of interest system wide.

So lets explore this further – lets say I use two arrays – one to
represent the stuff that must be output, and one to represent the
latest inputs read.

Then, I think, first prize would be the ability to “publish” that
information as a shared memory block, that can be accessed by other
python processes.  Then it will be possible to a priori “chop up
the ownership” of the various bits, so that a process can simply
monitor the bits of interest to it, setting or clearing the bits
of the outputs it is responsible for. In this way the work could
be divided amongst many processes.

Then, on a periodic basis, the I/O would be done, much like one
would do it in an embedded system using an interrupt driven ticker
routine.

That would be really cool.

Does anybody know how to get such memory sharing done in Python?
(Linux only)

- Hendrik



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


Re: setattr and getattr, when to use?

2008-08-26 Thread Bruno Desthuilliers

Jason Scheirer a écrit :
(snip)

The 5%
of your time when you are doing metaprogramming or other abuses of the
object system are when you use get/setattr.


What makes you label metaprogramming and get/setattr as abuses ???
--
http://mail.python.org/mailman/listinfo/python-list


Re: Total No. of Records in a File?

2008-08-26 Thread Bruno Desthuilliers

W. eWatson a écrit :
I have an ordinary text file with a CR at the end of a line, and two 
numbers in each line. Is there some way to determine the number of lines 
(records) in the file before I begin reading it?


How could you know how many times a given character appears in file 
without reading the whole file ?


You could of course store metadata about one file in another file[1], 
but then you'd have to read and parse this other file, and it might go 
out of sync.


[1] or at the begining of your 'data' file - but you still have to rad 
at least this part, and you still have the potential sync problem.


Or you could use a fixed-size binary format for your records, and try 
dividing the file size by the record size.


What's your concrete use case, exactly ?


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


Re: Total No. of Records in a File?

2008-08-26 Thread Bruno Desthuilliers

W. eWatson a écrit :

Fredrik Lundh wrote:

W. eWatson wrote:

I have an ordinary text file with a CR at the end of a line, and two 
numbers in each line. Is there some way to determine the number of 
lines (records) in the file before I begin reading it?


In the general case, no.  A file is just a bunch of bytes.  If you 
know that all lines have exactly the same length, you can of course 
fetch the file size and divide by the line size, but that doesn't work 
for arbitrary files.


Why do you need to know the number of lines before reading it, btw?

/F

Actually, it was a matter of curiosity, and maybe absent mindedness. I 
was envisioning a program where I might want to run up and down a file a 
lot, sometimes deleting a record interactively at the request of the 
user. However, I wanted to keep him alert to the total number of records 
remaining. However, in retrospect, I more likely do this with files in a 
folder. I also want him to be able to skip around in the Win OS folder 
by saying something like go forward 3 files. I'd like not to have to 
read all the files between the two points. The whole idea needs some 
more thinking.



The whole idea is that you should learn what a DBMS is good for, IMHO.
--
http://mail.python.org/mailman/listinfo/python-list


Re: A variables variables

2008-08-26 Thread Bruno Desthuilliers

castironpi a écrit :

On Aug 23, 7:25 pm, Gandalf [EMAIL PROTECTED] wrote:

how can I declare a variable with another variable  name?

for example  I will use PHP:

$a= hello;

$a_hello=baybay;

print ${'a_'.$a)  //output: baybay

how can i do it with no Arrays using  python

thanks!


Here's one idea.


a= 'hello'
a_hello= 'bayb'
print eval( 'a_'+ a )

bayb


Please avoid this kind of yucky ugly hacks.

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


Re: What is class method?

2008-08-26 Thread Bruno Desthuilliers

MeTheGameMakingGuy a écrit :

On Aug 24, 6:32 pm, Hussein B [EMAIL PROTECTED] wrote:

Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
--
class M:
 def method(cls, x):
pass

 method = classmethod(method)
--
Thank you for your time.


Firstly, don't use method = classmethod(method). Decorators are far
better. The following code has the same effect:

class M:
 @classmethod
 def method(cls, x):
  pass

Far more readable, right?


Yes, but will only work with Python = 2.4. There are cases where you 
want to keep compatibility with Python 2.3...



Class methods are useful if you've got lots of inheritance happening.
The first argument passed in is the class calling the method. Handy
for a mix-in: it can add methods affecting the actual class it's mixed
into, rather than messing with the mix-in itself.


I'm not sure I get your point here.

As far as I'm concerned, classmethods are useful anywhere you need to 
work on the class object itself.

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


Re: What is class method?

2008-08-26 Thread Bruno Desthuilliers

Maric Michaud a écrit :
(snip)

It is a common advice that staticmethod should not exist in python, as they do 
nothing compared to module level functions,


They do nothing more, but are accessible thru a class object instead 
of being accessible thru a module object. It sometimes happens to be 
useful (for a very very low value of 'sometimes' as far as I'm 
concerned, but still...)


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


Re: why in returns values for array and keys for dictionary

2008-08-26 Thread ++imanshu
On Aug 26, 11:52 am, Erik Max Francis [EMAIL PROTECTED] wrote:
 ++imanshu wrote:
      Wouldn't it be nicer to have 'in' return values (or keys) for both
  arrays and dictionaries. Arrays and Dictionaries looked so similar in
  Python until I learned this difference.

 It's because dealing with keys makes far more sense, since that's how
 the dictionary data structure works.  If you're doing this an awful lot
 -- whether testing for inclusion or iterating -- then you're probably
 using the wrong data structure.

Thanks for the detailed replies. Python seems to be taking the
pragmatic approach here instead of the pure one. And yes it makes more
sense.

Thanks,
++imanshu


 --
 Erik Max Francis  [EMAIL PROTECTED] http://www.alcyone.com/max/
   San Jose, CA, USA  37 18 N 121 57 W  AIM, Y!M erikmaxfrancis
    Well I have been puppetized / Oh how I have compromised
     -- Lamya

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


Re: generate methods at runtime, but the wrong one gets called

2008-08-26 Thread Bruno Desthuilliers

Maric Michaud a écrit :
(snip)

i don't get your design, it seems over-complicated to mee at first glance.



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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread John Machin
On Aug 26, 5:43 pm, Martin Marcher [EMAIL PROTECTED] wrote:
 On 2008-08-26 00:32:20, cnb wrote:

  Are dictionaries the same as hashtables?

 Yes, but there is nothing in there that does sane collision handling
 like making a list instead of simply overwriting.


Please clarify: (1) Nothing in where? In the Python dictionary
implementation? (2) What do you mean by sane collision handling?
What do you mean by simply overwriting?

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


Re: How to manipulate list of dictionary

2008-08-26 Thread Bruno Desthuilliers

Simon Brunning a écrit :

2008/8/26 ajak_yahoo [EMAIL PROTECTED]:

Need some help, I have a list of dictionary as below,

table = [{Part #:Washer,Po #:AE00128,qty:100},
 {Part #:Brake Pad,Po #:AE00154,qty:150},
 {Part #:Mesh,Po #:AE00025,qty:320},
 {Part #:Mouse,Po #:AE00207,qty:120},
 {Part #:Insulator,Po #:AE0013,qty:190}]

How to manipulate the table?

I need to search for the Po #, and display the result as below.


Part # : Mouse
Po #   : AE00207
Qty: 120 pcs


Well, that's a really bad data structure for what you want to do, but
you can do it with something like (untested):

wanted = 'AE00207'

for part in table:
if part['Po #'] == wanted:
print Part #:\t%(Part #)s\nPo #:\t%(Po #)s\nQty #:\t%(qty)s % part



Which will not be very efficient if you happen to have lot of items in 
your list and or a lot of searches to do.



The next solution is to maintain an index, ie:

def make_index(table, key):
index = {}
for record in enumerate(table):
index.setdefault(record[key], []).append(record)
return index

po_index = make_index(table, Po #)
results = po_index.get('AE00207', None)


But this won't scale up if you have millions of records. So the next 
next solution is to use a true database - either a RDBMS, or an embedded 
one like SQLite.


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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Diez B. Roggisch
Martin Marcher wrote:

 On 2008-08-26 00:32:20, cnb wrote:
 Are dictionaries the same as hashtables?
 
 Yes, but there is nothing in there that does sane collision handling
 like making a list instead of simply overwriting.

The term collision is rather well defined when talking about associative
arrays using hashing (which python's dicts are): it means that two distinct
keys produce the same hash-value, leading to a bucket collision. And of
course python deals with that sanely, and creates a list of objects inside
the bucket which is traversed and comparison is used to determine which
actual value to retrieve.

Python does not have a one key maps to a list of values-semantics - which
I consider the sane choice...

However, you can have that using the defaultdict for example:

listdict = defaultdict(list)

listdict[key].append(value)

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


logging exceptions

2008-08-26 Thread Alexandru Mosoi
why doesn't logging throw any exception when it should? how do I
configure logging to throw exceptions?

 try:
...   logging.fatal('asdf %d', '123')
... except:
...   print 'this line is never printed'
...
Traceback (most recent call last):
  File /Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py, line 744, in emit
msg = self.format(record)
  File /Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py, line 630, in format
return fmt.format(record)
  File /Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py, line 418, in format
record.message = record.getMessage()
  File /Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py, line 288, in getMessage
msg = msg % self.args
TypeError: int argument required
--
http://mail.python.org/mailman/listinfo/python-list


Python LDAP

2008-08-26 Thread Juan
Hi

I am trying to make a simple Python script using LDAP. The module is
imported OK, but when I call the function open or initialize, I get
this error:

Traceback (most recent call last):
  File /home/juan/workspace/amquare/src/nutum/amquare/amquare.py,
line 122, in module
conn.connect()
  File /home/juan/workspace/amquare/src/nutum/amquare/ldap_util.py,
line 39, in connect
self.conn = ldap.initialize(self.host, self.port)
  File /usr/lib/python2.5/site-packages/ldap/functions.py, line 87,
in initialize
return LDAPObject(uri,trace_level,trace_file,trace_stack_limit)
  File /usr/lib/python2.5/site-packages/ldap/ldapobject.py, line 70,
in __init__
self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri)
  File /usr/lib/python2.5/site-packages/ldap/functions.py, line 59,
in _ldap_function_call
result = func(*args,**kwargs)
LDAPError: (2, 'No such file or directory')

What file is not found? I have lots of searches but don't get any
answer. Anyone know how to solve this?

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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Ben Finney
cnb [EMAIL PROTECTED] writes:

 Are dictionaries the same as hashtables?

The 'dict' type in Python has certain behaviour, as specified in the
language reference. In CPython they are implemented as hash tables,
but I don't recall anything that specifies they *must* be implemented
that way.

So my answer would be maybe, but don't count on it. Write your
program to the specified behaviour of the language, not to the
underlying implementation.

-- 
 \“With Lisp or Forth, a master programmer has unlimited power |
  `\ and expressiveness. With Python, even a regular guy can reach |
_o__)   for the stars.” —Raymond Hettinger |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Is my thinking Pythonic?

2008-08-26 Thread Bruno Desthuilliers

Fredrik Lundh a écrit :

Bruno Desthuilliers wrote:

Given the lack of proper support for the descriptor protocol in 
old-style classes and a couple other diverging behaviors, I wouldn't 
say that advising newcomers to use new-style classes is so pointless.


Yeah, but if you don't need descriptors, new-style classes don't buy you 
anything  


Except being python-3000 ready wrt/ diverging behavious - like 
overriding __magic__ methods on a per-instance basis. Ok, this is 
certainly not a very common case, but still we've seen questions about 
this on this ng...



(except a slight slowdown in certain situations).
Dogmatic 


dogmatic ???

use 
of new-style classes (or any other new feature) isn't pythonic.


You're right to quote the word new here - how many years since Python 
grew a new object model explicitely intended to replace the original one ?

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


Re: Overwriting property- can't set attribute

2008-08-26 Thread Bruno Desthuilliers

norseman a écrit :

Gregor Horvath wrote:

Hi,

why is this code failing?

class B(object):
pass

B.testattr = property(lambda s:hallo)
b = B()
b.testattr = test


Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)

/tmp/python-14202ViU.py in module()
 14 B.testattr = property(lambda s:hallo)
 15 b = B()
--- 16 b.testattr = test
 17
 18

type 'exceptions.AttributeError': can't set attribute

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




b = B()   # synonyms


Not exactly, no. You probably missed the call operator applied to B.

(snip erroneous explanation).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overwriting property- can't set attribute

2008-08-26 Thread Bruno Desthuilliers

Gregor Horvath a écrit :

Hi,

why is this code failing?

class B(object):
pass

B.testattr = property(lambda s:hallo)
b = B()
b.testattr = test


Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)

/tmp/python-14202ViU.py in module()
 14 B.testattr = property(lambda s:hallo)
 15 b = B()
--- 16 b.testattr = test
 17
 18

type 'exceptions.AttributeError': can't set attribute



It's not failing, it's doing exactly what's expected. You made testattr 
a read-only property by not providing a setter.

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


Ctypes module - looking for a way to dynamically call exported function from a set of dlls

2008-08-26 Thread dudeja . rajat
Hi,

I'm using the ctypes module to load my dlls.

I have some 10 dlls the names of those are passed to a fucntion which
then loads the passed dll.

Now every dll has a getversion function.
eg: A.dll, B.dll, C.dll are the dlls
and GetVersion functions are as:
A_getVersion(), B_getVersion(),
C_getVesion()



The functionality I'm lookking for is that depending on the dll passed
the right getVersion should be passed.

I'm able to load the all the dlls passed to the function but I'm not
able to call the function names dynamically

Please help

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


RPCXML hide implementation.

2008-08-26 Thread x_O
Hi

I'm working recently with XMLRPC for python and It never was so easy.

But I've meet a obstacle. Because python is not giving us any
reasonable encapsulation mechanism, I have problems with hiding  some
part of the implementation.

When class has 2 methods and I want to make rpc private only ONE of
them. I can always use __name. But what in case when I really need to
use those two methods inside other class as a public, but not by RPC

Simple  code:
class RpcClass:
  def one(self): #visible by RPC, available as public for other class
return one
  def two(self): #INVISIBLE by RPC, available as public for other
class
return two

Server.register_instance(RpcClass())

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


properties with subscripted variables

2008-08-26 Thread Fabrizio Pollastri
Hi,
I work on the python module AVC (http://avc.inrim.it) useful for the
development of applications with GUIs. AVC is based on the property
mechanism: any a variable controlled by AVC is set as a property, so
when it is assigned by the application program, the __set__ function
is called and AVC does its job. This works fine with non sequence
types and with sequence types when are assigned as a whole, without
subscripting. When the assignment has a subscript, the __set__ method
is no more called. This is a limitation from the point of view of AVC.
My goal would be to be able to intercept (trigger a call to a method
of my module) any kind of variable assignment, even if it is a
sequence type with a subscript.
There is a way to reach this result with properties or with other
ways?

Best regards,
F. Pollastri
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Strinh Immutability Broken!

2008-08-26 Thread Hendrik van Rooyen

Gabriel Genellina:

To avoid altering the equilibrium of the whole universe, use
ctypes.create_string_buffer:
http://python.net/crew/theller/ctypes/tutorial.html#fundamental-data-types

Thanks Gabriel – looks like I really have to spend more time with that
excellent document.


Patrick Maupin:

Whenever I do low-level stuff like this, I'm in one of two modes:

Mode #1:  I'm using somebody else's C library and the overhead of
doing so is small.

Mode #2:  I need to code my own low-level stuff (for speed, IO access,
whatever).

This seems to be where I am at.


In mode 1, I try not to break out a compiler.  ctypes is great for
this, and the results are pure python to the extent that you can
give pure python to someone else with the same C library, and it will
work.  No muss, no fuss, no makefile, no question that ctypes is
awesome stuff.

In mode 2, I have to break out a compiler.  I almost never do this
without ALSO breaking out Pyrex.  Pyrex is also awesome stuff, and in
Pyrex, you can easily create a (new) Python string for your results
without having to worry about reference counting or any other really
nasty low level interpreter details.  You can code a lot of stuff in
pure Pyrex, and you can easily mix and match Pyrex and C.

Pyrex and ctypes are both tools which let me connect to non-Python
code without having to remember to handle Python interpreter internals
correctly.  If I can get by with ctypes, I do, but if I actually have
to code in something other than Python to get the job done, I bypass
ctypes and go straight for Pyrex.

Don’t know anything about Pyrex except that it is not in the
standard library on Suse – will try to read up on it. Thanks.

Terry Reedy:

 http://python.net/crew/theller/ctypes/tutorial.html#arrays

Which essentially is the bytearray type of 3.0.

How does it differ from plain old array.array(b,”The quick brown fox”)?

- Hendrik


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


Libraries for internal SOA components

2008-08-26 Thread Artur Siekielski
Hi.

I'm looking for libraries for implementing SOA components (not
necessery web services). Most of the components are not communicating
with the world. Language independence is not very important (Python
is everywhere :). Important requirement is ability to process requests
in parallel, and because we (of course) use CPython then simple
threading is not sufficient.

The solution with XMLRPC server from stdlib with ForkingMixin works,
but it seems it's not suited for production use. It has the
disadvantage of supporting simple types only. Pyro supports all Python
types but uses threading for parallelization only I think. This could
be overcomed of course (eg. using 'processing' package and worker
processes), but anybody uses Pyro for SOA?

Another option is to jump into Twisted world, but I would rather use a
library that I can use like I want than a framework. Anyway it seems
that even in Twisted I have to program parallelization by myself, like
in this example: http://www.artima.com/weblogs/viewpost.jsp?thread=230001
.

Any hints or advices? :)
--
http://mail.python.org/mailman/listinfo/python-list


Setting my Locale

2008-08-26 Thread Robert Rawlins
Good morning Guys,

 

I'm running python 2.5 on a Debian based system and I'm looking for your
advice on how to set the locale for my application. I've read through the
locale module documentation http://docs.python.org/lib/module-locale.html
and tried a couple of the examples but can't seem to get it working.

 

For instance, when I attempt to run the following code:

 

import locale

locale.setlocale(locale.LC_ALL, 'de_DE')

 

I get an exception raised by the application which says:

 

Traceback (most recent call last):

  File locale_test.py, line 2, in module

locale.setlocale(locale.LC_ALL, 'de_DE')

  File /usr/lib/python2.5/locale.py, line 478, in setlocale

return _setlocale(category, locale)

locale.Error: unsupported locale setting

 

My questions are; what would be causing this error? Do I need any additional
packages installed on the system for this locale support to work properly?
How can I get a list of available locales?

 

Many thanks for any advice guys,

 

Robert

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

Re: why in returns values for array and keys for dictionary

2008-08-26 Thread bearophileHUGS
++imanshu:
 Wouldn't it be nicer to have 'in' return values (or keys) for both
 arrays and dictionaries. Arrays and Dictionaries looked so similar in
 Python until I learned this difference.

D language works like you say, and it's awful. With a key you can find
its value, but given only the value you can't find its key.

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


Re: properties with subscripted variables

2008-08-26 Thread Bruno Desthuilliers

Fabrizio Pollastri a écrit :

Hi,
I work on the python module AVC (http://avc.inrim.it) useful for the
development of applications with GUIs. AVC is based on the property
mechanism: any a variable controlled by AVC is set as a property, so
when it is assigned by the application program, the __set__ function
is called and AVC does its job. This works fine with non sequence
types and with sequence types when are assigned as a whole, without
subscripting. When the assignment has a subscript, the __set__ method
is no more called.


Nope, but the __get__ method is.


This is a limitation from the point of view of AVC.
My goal would be to be able to intercept (trigger a call to a method
of my module) any kind of variable assignment, even if it is a
sequence type with a subscript.
There is a way to reach this result with properties or with other
ways?


The code:

  obj.prop[x] = y

is equivalent to:

  prop = obj.prop
  prop[x] = y

IOW, you just have to return from prop.__get__ a custom sequence type 
implementing __setitem__ the way you see fit.


Also, remember that properties are just one possible way to use the 
descriptor protocol to implement computed attributes. You can define 
your own descriptor objects.


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


[ANNOUNCE] pygtkmvc-1.2.2 has been released

2008-08-26 Thread Roberto Cavada

Version 1.2.2 of pygtkmvc has been released.

Project homepage:
http://pygtkmvc.sourceforge.net

Download:
http://sourceforge.net/projects/pygtkmvc/


==
About pygtkmvc
==

pygtkmvc is a fully Python-based implementation of the
Model-View-Controller (MVC) and Observer patterns for the PyGTK2
toolkit.

MVC is a pattern that can be successfully used to design and
develop well structured GUI applications. The MVC pattern
basically helps in separating semantics and data of the
application, from their representation.

The Observer pattern helps to weaken dependencies among parts that
should be separated, but need to be connected each other.

pygtkmvc provides a powerful and still simple infrastructure to
help designing and implement GUI applications based on the MVC and
Observer patterns.

The framework has been designed to be:

* Essential and small, it does only what it was designed for.
* Not an external dependency for your application: it fits in
  80KB and can be released along with it.
* Easy to understand and to use; fully documented.
* Portable: straightly runs under many platforms.

License: LGPL

===
About release 1.2.2
===

This is a minor release that fixes two major bugs about adapters.
A few new examples about adapters have been also added.

Thanks to Alessandro Dentella sandro TA e-den TOD it for reporting 
both bugs.


--
Roberto Cavada roboogle TA gmail TOD com

PA HREF=http://pygtkmvc.sourceforge.net;pygtkmvc 1.2.2/A -
Pygtk MVC is a thin, multiplatform framework that helps to design
and develop GUI applications based on the PyGTK toolkit. (26-Aug-08)
--
http://mail.python.org/mailman/listinfo/python-list


Re: RPCXML hide implementation.

2008-08-26 Thread skip
x Simple  code:
x class RpcClass:
x   def one(self): #visible by RPC, available as public for other class
x return one
x   def two(self): #INVISIBLE by RPC, available as public for other
x class
x return two

x Server.register_instance(RpcClass())

Just register the method you want to publish, not the entire instance.

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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread John Machin
On Aug 26, 7:36 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Martin Marcher wrote:
  On 2008-08-26 00:32:20, cnb wrote:
  Are dictionaries the same as hashtables?

  Yes, but there is nothing in there that does sane collision handling
  like making a list instead of simply overwriting.

 The term collision is rather well defined when talking about associative
 arrays using hashing (which python's dicts are): it means that two distinct
 keys produce the same hash-value, leading to a bucket collision. And of
 course python deals with that sanely, and creates a list of objects inside
 the bucket which is traversed and comparison is used to determine which
 actual value to retrieve.

I see neither buckets nor lists in the CPython svn trunk version of
dictobject.c and IIRC it's been using open addressing for a very long
time.
--
http://mail.python.org/mailman/listinfo/python-list


Split function for host:port in standard lib

2008-08-26 Thread Michael Ströder

HI!

Is there a function in the standard lib which can be used to split a 
string containg 'host:port' into a tuple (host,port) and also does this 
reliably for IPv6 addresses?


Ciao, Michael.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python LDAP

2008-08-26 Thread Michael Ströder

Juan wrote:

self.conn = ldap.initialize(self.host, self.port)

 [..]

LDAPError: (2, 'No such file or directory')


You have to pass in a LDAP URI as documented here:
http://python-ldap.sourceforge.net/doc/html/ldap.html#ldap.initialize

Use of compability function ldap.open() is deprecated and might vanish 
in future versions of python-ldap.


See also Demo/initialize.py in python-ldap's source distribution.

Ciao, Michael.
--
http://mail.python.org/mailman/listinfo/python-list


Date type in win32com?

2008-08-26 Thread Haeyoung Kim
Hi.

I'm migrating a VBScript into python.

How should I convert Date type parameter in VBScript's COM interface
with win32com?

I couldn't find any answer yet...

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


Re: logging exceptions

2008-08-26 Thread Rob Wolfe


Alexandru Mosoi napisał(a):
 why doesn't logging throw any exception when it should? how do I
 configure logging to throw exceptions?

  try:
 ...   logging.fatal('asdf %d', '123')
 ... except:
 ...   print 'this line is never printed'
 ...

[...]

You need to subclass your handler and redefine `handleError` method.
See: http://docs.python.org/lib/node409.html

HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list


Re: Split function for host:port in standard lib

2008-08-26 Thread Manuel Ebert

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

AFAIK port names cannot contain any colons, so python2.5's  
'host:port' .rsplit(':') should do the job. On  2.5 you probably  
need to do something like

s = addr.rindex(':')
host, port = addr[:s], addr[s+1:]

Best,
Manuel


On Aug 26, 2008, at 1:31 PM, Michael Ströder wrote:


HI!

Is there a function in the standard lib which can be used to split  
a string containg 'host:port' into a tuple (host,port) and also  
does this reliably for IPv6 addresses?


Ciao, Michael.
--
http://mail.python.org/mailman/listinfo/python-list



-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (Darwin)

iD8DBQFIs/KjcZ70OCIgLecRAlfpAJ9aTgw5sADVKHXHTahzE+4zyuTZhACghNi6
eYyGqdIl8ONJxznwJYZ78Cc=
=s8rW
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


What's your first choice if you have to write a C module for python?

2008-08-26 Thread 一首诗
Hi all,

I read this interesting post comparing Boost.Python with Pyd:

http://pyd.dsource.org/vsboost.html

What's your opinion about it?

What's your first choice when you have write a C/C++ module for Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Private attribute

2008-08-26 Thread Ken Starks

Steven D'Aprano wrote:

snip



def SomeClass(object):
_gridsize = 0.8


The leading underscore tells callers that they change the attribute at 
their own risk.


An even more Pythonic approach is to write your class that makes no 
assumptions about gridsize, and thus explicitly supports any reasonable 
grid size. 



The parent class, makes no assumption about grid-size, and I have put
a great deal of functionality there.

The methods of the derived class that depend on a gridsize of 8mm are
mostly concerned with standard LaTeX glyphs (from a specific font)
at standard LaTeX sizes.

I am fitting a small subset of them into my grid by hand, in a
way that I don't think could be easily automated even if I use the 
metric information. Not impossible, just too much hastle.


The general rationale of the project is 'pen-and-ink' algorithms
for arithmetic, on quadrille paper. It is to create figures that
will be imported into LaTeX later.

(By the way, it is perfectly easy to re-scale the figure after
the digits, carry-figures, and other glyphs are placed. So long
as you don't mind the font-size within the figure to
be out of kilter with the font-size of the main run of
LaTeX text.)

I hope this explains why I have decided on a Read-only attribute, the
first one ever, apart from a quick try-out when I started with Python.
And that was when Guido was still in Amsterdam.


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


Re: What's your first choice if you have to write a C module for python?

2008-08-26 Thread bearophileHUGS
[EMAIL PROTECTED]:
 I read this interesting post comparing Boost.Python with Pyd:
 http://pyd.dsource.org/vsboost.html
 What's your opinion about it?
 What's your first choice when you have write a C/C++ module for Python?

That's not exactly a post.
Pyd works well enough, it's easy to use and requires very little extra
code for the interface, I've used it several times. But it's designed
for D, not for C/C++, so in some situations it can be useless. For C/C+
+ you can find any kind of lib to wrap with Swig/ SIP/ Boost Python/
Cython/ etc, but you can't find much for D yet. And the D community is
very small, so there's just 1 person that updates Pyd, so updates are
slow, support limited (but it exists, on the #D IRC channel) and so
on. D surely isn't as complex as C++, and it's way nicer, but it's not
simple either, so learning it may require some time. Another thing to
think about is that C code sometimes may be even two times faster than
D code, so if max speed is essential, then D may not be the best
choice.

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


Sharing common memory space (In form of List) across the python processes.

2008-08-26 Thread Piyush Chechani
Hi,

Thanks for your reply Terry.

I am still not done with this problem. Please tell me can a server send a 
list object using socket programming to the requesting client?
If yes, how? I am getting the following error 
TypeError: send() argument 1 must be string or read-only buffer, 
not list

For sending list object I tried the following code: - 

Server Code: -
-
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( id(someList) )

# Our thread class:
class ClientThread ( threading.Thread ):

# Override Thread's __init__ method to accept the parameters needed:
   def __init__ ( self, channel, details ):

  self.channel = channel
  self.details = details
  threading.Thread.__init__ ( self )

   def run ( self ):

  print 'Received connection:', self.details [ 0 ]
  self.channel.send ( pickledList )
 
  self.channel.close()
  print 'Closed connection:', self.details [ 0 ]

# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )

# Have the server serve forever:
while True:
channel, details = server.accept()
print channel, details
ClientThread ( channel, details ).start()


Client Code: -
-
class ConnectionThread ( threading.Thread ):

   def run ( self ):

  # Connect to the server:
  client = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
  client.connect ( ( 'localhost', 2727 ) )
  #print 'Connected!!',client

  # Retrieve and unpickle the list object:
  lst= pickle.loads ( client.recv ( 1024 ) )

  # Close the connection
  client.close()

# Let's spawn a few threads:
for x in xrange ( 10 ):
   ConnectionThread().start()
-

In the above code I am able to get the id of the server List in the 
client, but can not access the content at the client. And if I send the 
pickled list to the client, it creates a new list at the client end, which 
is not desirable.

Please suggest how to share a in-memory list object across two different 
programs?

Thanks.
Piyush.
=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


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

Re: why in returns values for array and keys for dictionary

2008-08-26 Thread Lie
On Aug 26, 4:04 pm, ++imanshu [EMAIL PROTECTED] wrote:
 On Aug 26, 11:52 am, Erik Max Francis [EMAIL PROTECTED] wrote:

  ++imanshu wrote:
       Wouldn't it be nicer to have 'in' return values (or keys) for both
   arrays and dictionaries. Arrays and Dictionaries looked so similar in
   Python until I learned this difference.

  It's because dealing with keys makes far more sense, since that's how
  the dictionary data structure works.  If you're doing this an awful lot
  -- whether testing for inclusion or iterating -- then you're probably
  using the wrong data structure.

 Thanks for the detailed replies. Python seems to be taking the
 pragmatic approach here instead of the pure one. And yes it makes more
 sense.

Anyway, there is two obvious choice when dealing with dictionary
looping: return the keys and return the key and value. The python
designer thought that it is trivial to get the value from key so
returning both key and value, when the value might not be used at all,
is redundant and might cause a slow down. In the case where it is
actually needed for practicality (usually one-liner), then
dict.iteritems() is provided, in other cases where you don't need the
key (usually when you're applying a uniform function to dictionary or
to convert it to a list), dict.itervalues() is provided, and for
completeness dict.iterkeys() which is completely useless in a for-loop
is provided (the only case where it _might_ be useful is in
callbacks).

Anyway, in short (in code):
for key in dict:
print key, dict[key]

is exactly the same as:
for key, value in dict.iteritems():
print key, value

or
for key in dict:
value = dict[key]
print key, value
# the next line is not needed if you don't modify an immutable
value
dict[key] = value
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sharing common memory space (In form of List) across the python processes.

2008-08-26 Thread D'Arcy J.M. Cain
On Tue, 26 Aug 2008 18:18:53 +0530
Piyush Chechani [EMAIL PROTECTED] wrote:
 Please suggest how to share a in-memory list object across two different 
 programs?

Perhaps you want to investigate XML-RPC.  Check the docs for some
example scripts for both client and server.

P.S. Please drop the legal crap from your postings.  This is a public
list and such things are just a waste of space.

-- 
D'Arcy J.M. Cain [EMAIL PROTECTED] |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Filling in Degrees in a Circle (Astronomy)

2008-08-26 Thread Lie
On Aug 23, 6:12 am, W. eWatson [EMAIL PROTECTED] wrote:
 The other night I surveyed a site for astronomical use by measuring the
 altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees north
 clockwise around the site to 360 degrees, almost north again) of obstacles,
 trees. My purpose was to feed this profile of obstacles (trees) to an
 astronomy program that would then account for not sighting objects below the
 trees.

 When I got around to entering them into the program by a file, I found it
 required the alt at 360 azimuth points in order from 0 to 360 (same as 0).
 Instead I have about 25 points, and expected the program to be able to do
 simple linear interpolation between those.

 Is there some simple operational device in Python that would allow me to
 create an array (vector) of 360 points from my data by interpolating between
 azimuth points when necessary? All my data I rounded to the nearest integer.
 Maybe there's an interpolation operator?

 As an example, supposed I had made 3 observations: (0,0) (180,45) and
 (360,0). I would want some thing like (note the slope of the line from 0 to
 179 is 45/180 or 0.25):
 alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0
 az : 0, 1,    2,    3,              180

 Of course, I don't need the az.

 --
             Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

               (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
                Obz Site:  39° 15' 7 N, 121° 2' 32 W, 2700 feet

                      Web Page: www.speckledwithstars.net/

Linear interpolation is simple, any mathematician would know. It's
just like this:

hA = height at point A
hB = height at point B
hN = height at point N (what we're finding)
l = horizontal distance between A and B
n = horizontal position measured from A

hN = hA + ((n / l) * (hB - hA))

so:

def interpolate(n, A, B):
# A, B is two-tuple of (angle, height) of
# the nearest known points surrounding n
oA, hA = A
oB, hB = B
l = oB - oA
return hA + ((n / l) * (hB - hA))

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


Re: Best way to set/get an object property

2008-08-26 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :
(snip)
But it's quite rare to see double-underscore really private attributes 
in Python code. It is considered to go against the spirit of the language.


Not necessarily against the spirit - it's mostly than __name_mangling 
is only really useful when you want to protect a really vital 
implementation attribute from being *accidentaly* overridden, and mostly 
annoying anywhere else.


I'm told that in Java it is quite difficult to change a class from using 
public attributes to getters/setters,


That's an understatement. Java has *no* support for computed attributes, 
so you just can *not* turn a public attribute into a computed one.


and therefore many Java developers 
prefer to use getters/setters right from the beginning.


Truth is that they have no other choice if they want to be able to 
decouple implementation from interface.


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

Re: Programmatically exit the REPL

2008-08-26 Thread Alexander Schmolck
Without reading your post properly or having tried to do the same thing
myself: I think you might want to have a look at ipython; it gives a better
REPL and embedding ipython should give you plenty of hits as well.

Matthew Fitzgibbons [EMAIL PROTECTED] writes:

 I've got a pretty complex interactive command line program. Instead of writing
 my own REPL, I'm using the Python interpreter (an infinitely better solution).
 This program has two threads, a background thread and the REPL thread. When
 you call quit() or sys.exit() in the REPL thread, everything is perfectly
 happy. However, the background thread does some long-running jobs, and I want
 it to have the ability to exit the program when the job is complete. When I
 call quit() or sys.exit() from the background thread, the REPL merrily
 continues on its way.

 This is a very frustrating problem, so I'm hoping someone can shed some light
 on it. Am I missing something simple? Or is this just impossible? I don't see
 anything about breaking out of interact() in the code module docs.


 Here's a minimal example:

 #!/usr/bin/env python -i
 # You get the same behavior using code.interact()

 import sys
 import time
 import threading

 def end_the_program():
 # works if you call it from the REPL thread,
 # but not the background thread
 print called end_the_program()
 sys.exit()
 # quit() # using quit() rather than sys.exit()
  # results in identical behavior

 keep_going = True
 def runner():
 while keep_going:
 time.sleep(0.1)
 end_the_program()
 threading.Thread(target=runner).start()

 # end example


 Here's the console session (edited for clarity):

 Desktop$ ./exit_repl.py
 keep_going = False
 called end_the_program()
 # notice we didn't exit here
 end_the_program()
 called end_the_program()
 # but we did exit here
 Desktop$


 -Matt

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


Empece hacer un blog de python http://binsd.wordpress.com/

2008-08-26 Thread R2T2
La verdad
que me da un poco de vergüenza pero bueno no se como colaborar con la
comunidad
python entonces empecé hacer conjunto de entradas en mi blog para
todos aquellos que recién se inician en python.Aun no llegue
a explicar objetos pero estaría bueno que me digan si voy por buen
camino :-).

Desde
ya muchas gracias y perdón por las molestias.

la direccion del blog es http://binsd.wordpress.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with extension modules built in debug mode

2008-08-26 Thread bhood2
On Tue, 26 Aug 2008 08:20:44 +0200, Fredrik Lundh
[EMAIL PROTECTED] wrote:

[EMAIL PROTECTED] wrote:

 I've come to the conclusion that posting about Embedded Python on the
 Python forums is a complete waste of time.  I hope I can get some
 useful insights here.

(just curious, but what are the Python forums?  isn't the 
newsgroup/mailing list *the* Python forum?)

http://python-forum.org/pythonforum/index.php


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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Martin
On Tue, Aug 26, 2008 at 9:52 AM, cnb [EMAIL PROTECTED] wrote:
 On Aug 26, 9:43 am, Martin Marcher [EMAIL PROTECTED] wrote:
 On 2008-08-26 00:32:20, cnb wrote:

  Are dictionaries the same as hashtables?

 Yes, but there is nothing in there that does sane collision handling
 like making a list instead of simply overwriting.

 PS: your sig was *a bit* longer than you question. please don't do
 that...

  signature.asc
  1KViewDownload

 my what?

Hehe,

it was *my* sig... i was using some old box with a mut config that
still had the fortune script in it... sorry.

Anyway what I meant by collision handling was:

$ python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type help, copyright, credits or license for more information.
 l = {}
 l
{}
 l[a] = 12
 l[b] = 13
 l
{'a': 12, 'b': 13}
 l[a] = This is a collision
 l
{'a': 'This is a collision', 'b': 13}


As you see position a is simply overwritten. Probably sane doesn't
really apply because how could the python creators possibly know
whether I just want to overwrite the value or indeed want some form of
collision handling (talk about lists vs. trees with there
subforms...)...

If one would want that he/she/it could still subclass dict and do more magic.

/martin

-- 
http://www.xing.com/profile/Martin_Marcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.
--
http://mail.python.org/mailman/listinfo/python-list


python multitask

2008-08-26 Thread [EMAIL PROTECTED]
Hi !
I want use many comands in same python script .
I want to use openoffice and pyuno .
I try this
 cmdoo=openoffice.org -accept='socket,host=localhost,port=2002;urp;'
 subprocess.call(cmdoo, shell=True)
but i need to execute another comand and need to stop subprocess
Thank you !
--
http://mail.python.org/mailman/listinfo/python-list


GUI programming with python

2008-08-26 Thread zamil
Hello Everyone

It's my very first email to this group. i am a beginner programmer of
python. it it possible to build Desktop application using python.
Which IDE should i use for this purpose? I will be glad if anyone can
give link of python ebook.

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


atomic increment

2008-08-26 Thread Alexandru Mosoi
how can i do an atomic read+increment? something like

with lock:
   old = atomic_int
   atomic_int += 1

but in one operation
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ctypes-users] ctypes - loading 'librsvg-2-2.dll'

2008-08-26 Thread Martin (gzlist)
On 26/08/2008, Tim Grove [EMAIL PROTECTED] wrote:
 Any ideas why a particular dll won't load on Windows XP Pro using
  ctypes?

I'm going to take a stab in the dark here and suggest it's because you
have multiple (different) copies of iconv.dll on your PATH.

  l=CDLL(r'D:\SILSign\librsvg-2-2.dll')
  Traceback (most recent call last):
   File input, line 1, in module
   File C:\PYTHON25\LIB\ctypes\__init__.py, line 349, in __init__
 self._handle = _dlopen(self._name, mode)
  WindowsError: [Error 127] The specified procedure could not be found

I get this on my current setup, where I've been messing around trying
to recompile lynx against iconv. I also get a popup saying The
procedure entry point libiconv_set_relocation_prefix could not be
located in the dynamic link library iconv.dll.

Doing this worked for me:

C:\set PATH=C:\Program Files\Common Files\GTK\2.0\bin
C:\C:\Python24\python.exe -c import ctypes; print
ctypes.CDLL('librsvg-2-2')
CDLL 'librsvg-2-2', handle 68e4 at bd9b50

Change the paths to your equivalents and try it, see if you have the
same or a similar dependency problem.

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


libxml2dom - parsing maligned html

2008-08-26 Thread bruce
Hi...

I'm using quick test with libxml2dom

===
import libxml2dom

aa=libxml2dom.parseString(foo)
ff=libxml2dom.toString(aa)

print ff
===

--
when i start, foo is:
html
body
/body
/html

html
body
.
.
.
/body
/html
---
when i print ff it's:
html
body
/body
/html
---

so it's as if the parseString only reads the initial html tree. i've
reviewed as much as i can find regarding libxml2dom to try to figure out how
i can get it to read/parse/handle both html trees/nodes.

i know, the html is maligned/screwed-up, but i can't seem to find any app
(tidy/beautifulsoup) that can know which one of the html trees to throw
out/remove!!

technically, both html trees are valid, it's just that they both shouldn't
be in the file!!!

thoughts/comments appreciated

thanks


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


python portable installation?

2008-08-26 Thread luismi

Hi,

I have searched the online manuals, faqs and forums, but i haven't
found a satisfactory explanation ... most probably my fault ;)

I have found 2 projects, one commercial and another free, that deal
with the installation and running of python code on portable/removable
devices, my questions are:
(1) Is this scenario not yet contemplated in the official releases,
and
(2) Why is such a big issue?

Will appreciate your comments,
Thanks in advance

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


Re: libxml2dom - parsing maligned html

2008-08-26 Thread Paul Boddie
On 26 Aug, 17:28, bruce [EMAIL PROTECTED] wrote:
 so it's as if the parseString only reads the initial html tree. i've
 reviewed as much as i can find regarding libxml2dom to try to figure out how
 i can get it to read/parse/handle both html trees/nodes.

Maybe there's some possibility to have libxml2 read directly from a
file descriptor and to stop after parsing the first document, leaving
the descriptor open; currently, this isn't supported by libxml2dom,
however. Another possibility is to feed text to libxml2 until it can
return a well-formed document, which I do as part of the
libxml2dom.xmpp module, but I don't really support this feature in the
public API.

Again, improvements to libxml2dom may happen if I find the time to do
them.

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


Re: atomic increment

2008-08-26 Thread Diez B. Roggisch
Alexandru  Mosoi wrote:

 how can i do an atomic read+increment? something like
 
 with lock:
old = atomic_int
atomic_int += 1
 
 but in one operation

As above - the lock (under the assumption that it is actually a
threading.Lock) will ensure that.

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


Re: libxml2dom - parsing maligned html

2008-08-26 Thread Stefan Behnel
bruce wrote:
 I'm using quick test with libxml2dom
 
 ===
 import libxml2dom
 
 aa=libxml2dom.parseString(foo)
 ff=libxml2dom.toString(aa)
 
 print ff
 ===
 
 --
 when i start, foo is:
 html
 body
 /body
 /html
 
 html
 body
 .
 .
 .
 /body
 /html
 ---
 when i print ff it's:
 html
 body
 /body
 /html
 ---
 
 so it's as if the parseString only reads the initial html tree. i've
 reviewed as much as i can find regarding libxml2dom to try to figure out how
 i can get it to read/parse/handle both html trees/nodes.
 
 i know, the html is maligned/screwed-up, but i can't seem to find any app
 (tidy/beautifulsoup) that can know which one of the html trees to throw
 out/remove!!
 
 technically, both html trees are valid, it's just that they both shouldn't
 be in the file!!!

What about splitting the string on html and them parsing each part on its 
own?

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


Re: python portable installation?

2008-08-26 Thread Fredrik Lundh

luismi wrote:


I have searched the online manuals, faqs and forums, but i haven't
found a satisfactory explanation ... most probably my fault ;)

I have found 2 projects, one commercial and another free, that deal
with the installation and running of python code on portable/removable
devices, my questions are:
(1) Is this scenario not yet contemplated in the official releases,
and
(2) Why is such a big issue?


there's no problem putting a python program, including a full runtime, 
anywhere on any disk.  the above tools simply streamline the process.


/F

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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Cameron Laird
In article [EMAIL PROTECTED],
Diez B. Roggisch [EMAIL PROTECTED] wrote:
Martin Marcher wrote:

 On 2008-08-26 00:32:20, cnb wrote:
 Are dictionaries the same as hashtables?
.
.
.
Python does not have a one key maps to a list of values-semantics - which
I consider the sane choice...

However, you can have that using the defaultdict for example:

listdict = defaultdict(list)

listdict[key].append(value)

Diez

?  I'm lost.  As I understand your terms, Python's dictionaries
map keys to objects, but you would prefer that Python's 
dictionaries map keys only to lists of values.  That *sounds* 
like a complexification, at best.  Are you trying to make a
point about implementation aligning with semantics?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Fredrik Lundh

Martin Marcher wrote:


Are dictionaries the same as hashtables?


Yes, but there is nothing in there that does sane collision handling
like making a list instead of simply overwriting.


are you sure you know what collision handling means in this context?

/F

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


Re: File copying from a menu

2008-08-26 Thread Brandon
Ok, below is a portion of the code that first (near as I can tell because I 
had nothign to do with desgining the program) sets up the menu 
(setupMenuBar) and then adds the commands to be used with the items:

def setupMenuBar(self):
menubar = self.menuBar()
file_ = menubar.addMenu(File)
file_.addAction(self.importEx)
file_.addAction(self.exitAct)

def createActions(self):
fileMenu = QtGui.QMenu(self.tr(File), self)

self.importEx = QtGui.QAction(self.tr(Import Excel Document), 
self)
self.importEx.setShortcut(self.tr(Ctrl+E))
self.importEx.setStatusTip(self.tr(Import Excel Document))
self.connect(self.importEx, QtCore.SIGNAL(triggered()), 
self.importExcel)

self.exitAct = QtGui.QAction(self.tr(Exit), self)
self.exitAct.setShortcut(self.tr(Ctrl+Q))
self.exitAct.setStatusTip(self.tr(Exit the application))
self.connect(self.exitAct, QtCore.SIGNAL(triggered()), self, 
QtCore.SLOT(close()))

Fredrik Lundh [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Brandon wrote:

 I'm attempting to have a file copied from a menu selection.  The menu 
 already exists, but it won't even create the menu item.  If anyone has 
 any ideas, please let me know.

 try cutting down your code to a minimal example that illustrates the 
 problem, and post that code (that'll also allow us to figure out what 
 library you're using to create the menu...).

 /F
 


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


Re: GUI programming with python

2008-08-26 Thread Alan Franzoni
zamil was kind enough to say:

[cut]

If your needs are very basic, you can stick with the tk module that comes
with python. It's not really feature-packed, but it's maintained and pretty
cross-platform.

Otherwise, you can pick any supported widget set you like and use the
proper python bindings. You didn't tell us which OS you'd work with, hence
we can't tell you what's the best choice (if there's any).

BTW you should be able to enjoy GTK+, QT or Swing (if using Jython on Java)
or anything found in MS.NET (if using IronPython) - or you can go for
wxPython as well.

GUI Designers are widget-set related - I can suggest gazpacho for GTK+.

-- 
Alan Franzoni [EMAIL PROTECTED]
-
Remove .xyz from my email in order to contact me.
-
GPG Key Fingerprint:
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's your first choice if you have to write a C module for python?

2008-08-26 Thread Ulrich Eckhardt
一首诗 wrote:
 I read this interesting post comparing Boost.Python with Pyd:
 
 http://pyd.dsource.org/vsboost.html
 
 What's your opinion about it?
 
 What's your first choice when you have write a C/C++ module for Python?

There is no such thing as a C/C++ language. Seriously, both are really
different and require different approaches. That said, when writing a C++
module I use Boost.Python, for one because Boost is already part of many
C++ projects but also because it is simply very easy and convenient to use.

There is another alternative, ctypes, which also works but it IMHO brings
many of the disadvantages of C to Python. In particular those are manual
resource management and lack of exceptions. Looking at Boost.Python though,
you can simply throw a C++ exception and it gets mapped to a Python
exception, and resource management is also a non issue since you can make
ownership transfers explicit.

Now, concerning pyd, I think you are comparing apples to oranges. If you had
asked which language I would chose to write a Python plugin, that would
have been a totally different thing. To that, the answer is in order of
preference:
 1. Python ;)
 2. C++ with Boost.Python
 3. C with ctypes

cheers

Uli


-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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

Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Fredrik Lundh

Diez B. Roggisch wrote:


I don't know the exact names of the involved structures - I named them
liberally from my understanding of how associative arrays based on hashing
are implemented. But the below code shows that hash-collisions can occur
without corrupting data


http://en.wikipedia.org/wiki/Open_addressing

Open addressing, or closed hashing, is a method of collision resolution 
in hash tables. With this method a hash collision is resolved by 
probing, or searching through alternate locations in the array (the 
probe sequence) until either the target record is found, or an unused 
array slot is found, which indicates that there is no such key in the 
table.


/F

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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Diez B. Roggisch
Cameron Laird wrote:

 In article [EMAIL PROTECTED],
 Diez B. Roggisch [EMAIL PROTECTED] wrote:
Martin Marcher wrote:

 On 2008-08-26 00:32:20, cnb wrote:
 Are dictionaries the same as hashtables?
 .
 .
 .
Python does not have a one key maps to a list of values-semantics -
which I consider the sane choice...

However, you can have that using the defaultdict for example:

listdict = defaultdict(list)

listdict[key].append(value)

Diez
 
 ?  I'm lost.  As I understand your terms, Python's dictionaries
 map keys to objects, but you would prefer that Python's
 dictionaries map keys only to lists of values.  That *sounds*
 like a complexification, at best.  Are you trying to make a
 point about implementation aligning with semantics?

The OP seems to want that (or at least sees it as one of two viable design
choices), see his other answer in this thread.

I certainly *don't* agree with that, I merely pointed out that python comes
with means to easily create such a data-structure in the case it is needed.

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


Best idiom for looping over input?

2008-08-26 Thread mh
What's the best Python idiom for this C construct?

while ((x = next()) != END) {

}

Now I'm doing

x = next()
while x != END:

x = next()

There's not an iterator for this function, or I would
just use

for x in ...

Many TIA!
Mark

-- 
Mark Harrison
Pixar Animation Studios
--
http://mail.python.org/mailman/listinfo/python-list


Newbie needs help

2008-08-26 Thread frankrentef
Greetings all,

I'm wanting to maintain what values in one file and call them in
another.  The purpose being to keep a single location where url's,
login's and passwords can be maintained, then called as needed from
another file.

In file #1 I have...

import time
import os
import sys

url = 'http://zoo/'

adminlogin = 'Zebra'
adminpassword = 'Zebra12$'


-

In file #2 I have the following...

from cPAMIE import PAMIE

#Imports - used to setup / control finding files
import time
import os
import sys
import loginout#name of the file retaining all url/login info
from log import log

#Create New Pamie Object
ie=PAMIE()
ie=Visible =1
t=time

adminlogin (ie,url)
if ie.findText ('Site Status: Active'):
log ('PASSED -- ADMIN Module - ADMIN Login  Admin Tab Navigation
Successful')
else:
log ('WARNING -- ADMIN Module Login  Admin Tab Navigation
FAILED')
time.sleep(2)



What am I doing incorrectly to not have file two log in when
executed.  All files are in the same directory.   Keep it simple...
I'm new at this.

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


Re: Return a string result with out breaking loop

2008-08-26 Thread Andrew

Hi I have done this without error

:D

Yield returns the result I am looking for... however it does not 
continue looping. It does the same thing as return would


any suggestions

my code is as follows

serveraddr = ('', )
srvr = ThreadingServer(serveraddr, SimpleXMLRPCRequestHandler, 
allow_none=True)


srvr.register_instance(theApp())

srvr.register_introspection_functions()

def watchos(path_to_watch=C:\\):
#get path or maintain current path of app
FILE_LIST_DIRECTORY = 0x0001
try: path_to_watch or .
except: path_to_watch = .
path_to_watch = os.path.abspath(path_to_watch)

out1 = Watching %s at %s % (path_to_watch, time.asctime()) + \n\n
# FindFirstChangeNotification sets up a handle for watching
#  file changes.
while 1:

hDir = win32file.CreateFile (
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)

change_handle = win32file.ReadDirectoryChangesW (
hDir,
1024,
True,#Heap Size include_subdirectories,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None
)

# Loop forever, listing any file changes. The WaitFor... will
#  time out every half a second allowing for keyboard interrupts
#  to terminate the loop.
ACTIONS = {
1 : Created,
2 : Deleted,
3 : Updated,
4 : Renamed from something,
5 : Renamed to something
}

results = change_handle
for action, files in results:
full_filename = os.path.join(path_to_watch, files)
theact = ACTIONS.get(action, Unknown)
out2 = str(full_filename) ++ str(theact)
yield str(out2)

servg = watchos()
srvr.register_function(servg.next, 'watchos')

srvr.register_multicall_functions()
srvr.serve_forever()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programmatically exit the REPL

2008-08-26 Thread Matthew Fitzgibbons

Alexander Schmolck wrote:

Without reading your post properly or having tried to do the same thing
myself: I think you might want to have a look at ipython; it gives a better
REPL and embedding ipython should give you plenty of hits as well.



Thanks for the tip; I hadn't heard of ipython before. I will certainly 
check it out. However, if anyone knows how to break out of the 
interactive interpreter from another thread, I'd still very much like to 
hear about it. :)


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


Re: Best idiom for looping over input?

2008-08-26 Thread Jean-Paul Calderone

On Tue, 26 Aug 2008 16:42:30 GMT, [EMAIL PROTECTED] wrote:

What's the best Python idiom for this C construct?

   while ((x = next()) != END) {
   
   }

Now I'm doing

   x = next()
   while x != END:
   
   x = next()

There's not an iterator for this function, or I would
just use

   for x in ...



Use the magical second parameter to the `iter´ builtin:

   for x in iter(next, END):
   ...

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

Re: Newbie needs help

2008-08-26 Thread Eric Wertman
Is the loginout file named loginout.py ?  It needs to be for the
import to work.  If the import works, you have to refer to those
variables within the right namespace,  ie :   loginout.url,
loginout.adminlogin,  etc.



On Tue, Aug 26, 2008 at 12:46 PM, frankrentef [EMAIL PROTECTED] wrote:
 Greetings all,

 I'm wanting to maintain what values in one file and call them in
 another.  The purpose being to keep a single location where url's,
 login's and passwords can be maintained, then called as needed from
 another file.

 In file #1 I have...

 import time
 import os
 import sys

 url = 'http://zoo/'

 adminlogin = 'Zebra'
 adminpassword = 'Zebra12$'


 -

 In file #2 I have the following...

 from cPAMIE import PAMIE

 #Imports - used to setup / control finding files
 import time
 import os
 import sys
 import loginout#name of the file retaining all url/login info
 from log import log

 #Create New Pamie Object
 ie=PAMIE()
 ie=Visible =1
 t=time

 adminlogin (ie,url)
 if ie.findText ('Site Status: Active'):
log ('PASSED -- ADMIN Module - ADMIN Login  Admin Tab Navigation
 Successful')
 else:
log ('WARNING -- ADMIN Module Login  Admin Tab Navigation
 FAILED')
 time.sleep(2)



 What am I doing incorrectly to not have file two log in when
 executed.  All files are in the same directory.   Keep it simple...
 I'm new at this.

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

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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Chris Mellon
On Tue, Aug 26, 2008 at 11:12 AM, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Martin Marcher wrote:

 Are dictionaries the same as hashtables?

 Yes, but there is nothing in there that does sane collision handling
 like making a list instead of simply overwriting.

 are you sure you know what collision handling means in this context?

I think the confusion comes from thinking that dictionaries are
(really) hash tables and thus that things like collision handling are
exposed to the user of the data structure. In this sense, no,
dictionaries are *not* hash tables. They are mappings of keys to
values, and they use hash tables as part of their implementation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: extract text from ods TableCell using odfpy

2008-08-26 Thread norseman

frankentux wrote:

Ok. Sorted it out, but only after taking a round trip over
xml.minidom. Here's the working code:

#!/usr/bin/python
from odf.opendocument import Spreadsheet
from odf.opendocument import load
from odf.table import TableRow,TableCell
from odf.text import P
doc = load(/tmp/match_data.ods)
d = doc.spreadsheet
rows = d.getElementsByType(TableRow)
for row in rows[:2]:
cells = row.getElementsByType(TableCell)
for cell in cells:
tps = cell.getElementsByType(P)
if len(tps)  0:
for x in tps:
print x.firstChild
--
http://mail.python.org/mailman/listinfo/python-list


=
cd /opt
find . -name *odf* -print
(empty)
cd /usr/local/lib/python2.5
find . -name *odf* -print
(empty)


OK - where is it? :)


Steve
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best idiom for looping over input?

2008-08-26 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


What's the best Python idiom for this C construct?

while ((x = next()) != END) {

}


iter is your friend:

 for x in iter(next, END):
 ...

details:

 help(iter)
Help on built-in function iter in module __builtin__:

iter(...)
iter(collection) - iterator
iter(callable, sentinel) - iterator

Get an iterator from an object.  In the first form, the
argument must supply its own iterator, or be a sequence.
In the second form, the callable is called until it
returns the sentinel.

/F

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


sum up numbers in a list

2008-08-26 Thread sharon kim
hi all,

i have a list, for example;

 L=[]
 L.append('10')
 L.append('15')
 L.append('20')
 len(L)
3
 print L
['10', '15', '20']

is there a way to sum up all the numbers in a list?  the number of objects
in the list is vary, around 50 to 60. all objects are 1 to 3 digit positive
numbers.

all i can think of is check the length of the list (in the above example,
3), then L[0]+L[1]+L[2] ..

is there a better way to do the job? thanks.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Return a string result with out breaking loop

2008-08-26 Thread Fredrik Lundh

Andrew wrote:

Yield returns the result I am looking for... however it does not 
continue looping. It does the same thing as return would


the XML-RPC protocol doesn't really support your use case; for each 
call, the client issues a complete request package, and the server 
produces a complete response in return.


/F

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


Reading from text file

2008-08-26 Thread A. Joseph
I want to read from text file, 25 lines each time i press enter key,
just like the python documentation.

i`m using Python 2.5, Windows XP

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


  1   2   3   >