Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
Paul Rubin wrote:

> Steven D'Aprano  writes:
>> It is never
>> correct to avoid using "is" when you need to compare for identity.
> 
> When is it ever necessary to compare for identity?

Is that a trick question? The obvious answer is, any time you need to.

The standard library has dozens of tests like:

something is None 
something is not None

Various standard modules include comparisons like:

if frame is self.stopframe:
if value is not __UNDEF__:
if b is self.exit:
if domain is Absent:
if base is object:
if other is NotImplemented:
if type(a) is type(b):

although that last one is probably better written using isinstance() or
issubclass(). I have no doubt that there are many more examples.

Comparing by identity are useful for interning objects, for testing that
singletons actually are singletons, for comparing functions with the same
name, for avoiding infinite loops while traversing circular data
structures, and for non-destructively testing whether two mutable objects
are the same object or different objects.



-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread alex23
On Mar 7, 10:57 am, s...@pobox.com wrote:
> Right.  Again though, when newcomers conflate the concepts they can deceive
> themselves into thinking "is" is just a faster "==".

But _you_ only _just_ stated "It does have some (generally small)
performance ramifications as
well" and provided timing examples to show it. Without qualification.

And you're wondering why these mythical newcomers might be confused...
--
http://mail.python.org/mailman/listinfo/python-list


Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
s...@pobox.com wrote:

> Steven> Mutable versus immutable is irrelevant. The complexity of the
> Steven> object is irrelevant. The phase of the moon is irrelevant. The
> Steven> *only* relevant factor is the programmer's intention:
> 
> Which for a new user not familiar with the differing concepts of "is" and
> "==" can lead to mistakes.

Right. And for newbies unfamiliar with Python, they might mistakenly think
that ^ is the exponentiation operator rather than **.

So what do we do? Do we teach them what ^ actually is, or give them bad
advice "Never call ^" and then watch them needlessly write their own
exponentiation function?

Do we then defend this terrible advice by claiming that nobody needs
exponentiation? Or that only experts need it? Or that it's necessary to
tell newbies not to use ^ because they're only newbies and can't deal with
the truth?

No, of course not. But that's what some of us are doing with regard to "is".
Because *some* newbies are ignorant and use "is" for equality testing, we
patronisingly decide that *all* newbies can't cope with learning what "is"
really is for, give them bad advice, and thus ensure that they stay
ignorant longer.


> Steven> If you find it difficult to think of a reason for testing for
> Steven> identity, you're right, there aren't many. Since it's rare to
> Steven> care about identity, it should be rare to use "is". But in the
> Steven> few times you do care about identity, the correct solution is
> to Steven> use "is" no matter what sort of object it happens to be. It
> Steven> really is that simple.
> 
> Right.  Again though, when newcomers conflate the concepts they can
> deceive themselves into thinking "is" is just a faster "==".

Then teach them the difference, don't teach them superstition.



-- 
Steven

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


Re: Should I use stackless python or threads?

2009-03-06 Thread alex23
On Mar 7, 9:35 am, Minesh Patel  wrote:
> I need to monitor each directory for the latest install, take it and
> go perform some tests on a specific machine. I would like these
> testing tasks to run concurrently for the obvious reasons.

There are two other options to consider:
 * greenlet, which has come out of the Stackless project:
http://codespeak.net/py/dist/greenlet.html
 * circuits, which comes with an iNotify driver:
http://trac.softcircuit.com.au/circuits/browser/circuits/lib/drivers/inotify_driver.py

Both of these libraries favour concurrency over threading, I believe.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help cleaning up some code

2009-03-06 Thread Paul Rubin
"andrew cooke"  writes:
> def copy(src, dst, name, quote_none=False):
>   value = src[name]
>   dst[name] = 'None' if quote_none and value is None else value

def copy(src, dst, name, default=None):
  value = src[name]
  dst[name] = value if value is not None else default

> copy(row, ad, name, quote_none=True)

  copy(row, ad, name, default='None')
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help cleaning up some code

2009-03-06 Thread oscar deits
Thanks a lot! that copy function is a really neat trick!

Yes the ni's are sorted, and yes the query SHOULD be the one to limit it to
just one set of ni's; however, i am having trouble implementing that in sql.
I am using sqlite3 atm and right now i have a very large select statment the
gets me what i want, i just dont know how to filter it again base on data
that is from the result itself. I THINK normally one would select into a
temporary table then filter it from there, but i am not sure.

On Fri, Mar 6, 2009 at 9:43 PM, andrew cooke  wrote:

> odeits wrote:
> > I am looking to clean up this code... any help is much appreciated.
> > Note: It works just fine, I just think it could be done cleaner.
> >
> > The result is a stack of dictionaries. the query returns up to
> > STACK_SIZE ads for a user. The check which i think is very ugly is
> > putting another contraint saying that all of the ni have to be the
> > same.
> >
> > stack = []
> > rows = self.con.execute(adquerystring,(user,STACK_SIZE)).fetchall()
> > for row in  rows:
> > ad = dict()
> > ad['ni'] = row['ni']
> > ad['adid'] = row['adid']
> > ad['rundateid'] = row['rundateid']
> > ad['rundate'] = row['rundate']
> > if row['city'] is None:
> > ad['city'] = 'None'
> > else:
> > ad['city'] = row['city']
> > if row['state'] is None:
> > ad['state'] = 'None'
> > else:
> > ad['state'] = row['state']
> > ad['status'] = row['status']
> > try:
> > if stack[0]['ni'] != ad['ni']:
> > break;
> > except IndexError:
> > pass
> > stack.append(ad)
>
> NI = 'ni'
>
> def copy(src, dst, name, quote_none=False):
>  value = src[name]
>  dst[name] = 'None' if quote_none and value is None else value
>
> stack = []
> for row in self.con.execute(adquerystring,(user,STACK_SIZE)).fetchall():
>  ad = dict()
>  for name in (NI, 'adid', 'rundateid', 'rundate', 'status'):
>copy(row, ad, name)
>  for name in ('city', 'state'):
>copy(row, ad, name, quote_none=True)
>  if stack and stack[0][NI] != ad[NI]:
>break
>  stack.append(ad)
>
> but couldn't you change the query so that it only returns a single 'ni'?
>
> also, do you really want to break, or just skip the append?  maybe you
> want:
>
>  if not stack or stack[0]['ni'] == ad['ni']:
>stack.append(ad)
>
> or perhaps the 'ni' are sorted (in which case what you are doing makes
> some sense).
>
> andrew
>
>
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> >
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help cleaning up some code

2009-03-06 Thread andrew cooke
odeits wrote:
> I am looking to clean up this code... any help is much appreciated.
> Note: It works just fine, I just think it could be done cleaner.
>
> The result is a stack of dictionaries. the query returns up to
> STACK_SIZE ads for a user. The check which i think is very ugly is
> putting another contraint saying that all of the ni have to be the
> same.
>
> stack = []
> rows = self.con.execute(adquerystring,(user,STACK_SIZE)).fetchall()
> for row in  rows:
> ad = dict()
> ad['ni'] = row['ni']
> ad['adid'] = row['adid']
> ad['rundateid'] = row['rundateid']
> ad['rundate'] = row['rundate']
> if row['city'] is None:
> ad['city'] = 'None'
> else:
> ad['city'] = row['city']
> if row['state'] is None:
> ad['state'] = 'None'
> else:
> ad['state'] = row['state']
> ad['status'] = row['status']
> try:
> if stack[0]['ni'] != ad['ni']:
> break;
> except IndexError:
> pass
> stack.append(ad)

NI = 'ni'

def copy(src, dst, name, quote_none=False):
  value = src[name]
  dst[name] = 'None' if quote_none and value is None else value

stack = []
for row in self.con.execute(adquerystring,(user,STACK_SIZE)).fetchall():
  ad = dict()
  for name in (NI, 'adid', 'rundateid', 'rundate', 'status'):
copy(row, ad, name)
  for name in ('city', 'state'):
copy(row, ad, name, quote_none=True)
  if stack and stack[0][NI] != ad[NI]:
break
  stack.append(ad)

but couldn't you change the query so that it only returns a single 'ni'?

also, do you really want to break, or just skip the append?  maybe you want:

  if not stack or stack[0]['ni'] == ad['ni']:
stack.append(ad)

or perhaps the 'ni' are sorted (in which case what you are doing makes
some sense).

andrew


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


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


Re: how to prevent python import from looking into the current directory

2009-03-06 Thread Carl Banks
On Mar 6, 1:54 am, Ben Finney 
wrote:
> (Could you please set a valid email address for people to contact you
> if necessary?)
>
> TP  writes:
> > I would like to prevent the loading of modules in the current
> > directory.
>
> You will, I think, like the new distinction between “absolute” and
> “relative” imports http://www.python.org/dev/peps/pep-0328/>.

He might, but it won't help him with his problem.  Relative imports
aren't involved in this situation.


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


Re: wxPython fast and slow

2009-03-06 Thread Lie Ryan

iu2 wrote:


Do you have any idea of what is going wrong?



I think this might be related to the OS's process prioritization, 
focused Windows would get more priority than background window.

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


Re: create boolean

2009-03-06 Thread Grant Edwards
On 2009-03-07, Rhodri James  wrote:
> On Fri, 06 Mar 2009 15:34:08 -, Grant Edwards  wrote:
>
>> On 2009-03-06, Fencer  wrote:
>>
>>> Hi, I need a boolean b to be true if the variable n is not
>>> None and not an empty list, otherwise b should be false.
>>
>>> I ended up with:
>>
>>> b = n is not None and not not n
>>
>> I'd do it like this:
>>
>>   b = (n is not None) and (n != [])
>
> The second comparison isn't actually necessary, since an
> empty list is True and a non-empty one False.
>
>b = (n is not None) and n
>
> Putting the comparison in does make the code slightly less
> "magic", though, so it's not a bad idea to do it!

Putting in the second comparison in makes the code match the
stated requirement.  Otherwise you have to start making
assumptions about what n might be besides None or the empty
list.

-- 
Grant

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


Re: python image - ignore values in resize

2009-03-06 Thread Lie Ryan

Travis Kirstine wrote:

I have be attempting to resize (downsample) a RGB image using the
python image library resize function.  Everything works fine but I
would like to exclude black values 0,0,0 from the calculations.  I
have tried creating a alpha mask based on black values then performing
the resize but that only create partially transparent tiles in the
regions that had black values


Crop the image first.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Should I use stackless python or threads?

2009-03-06 Thread Lie Ryan

Minesh Patel wrote:

On Fri, Mar 6, 2009 at 3:16 PM, Jean-Paul Calderone  wrote:

On Fri, 6 Mar 2009 14:50:51 -0800, Minesh Patel  wrote:

I am trying to figure out the best approach to solve this problem:

I want to poll various directories(can be run in the main thread).
Once I notice a file has been added to any directory, I grab a lock,
spawn a thread to go perform the necessary actions, and then release
the lock.

That's not a description of a problem.  That's a description of a potential
solution.  What problem are you trying to solve?



I have a build system that is outputting various forms of
installations in a particular directory structure, e.g. /pxe-installs,
/iso-install, /dd-installs, etc...

I need to monitor each directory for the latest install, take it and
go perform some tests on a specific machine. I would like these
testing tasks to run concurrently for the obvious reasons.


Why not use subprocess. For each update to the directory you spawn a new 
subprocess.

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


Help cleaning up some code

2009-03-06 Thread odeits
I am looking to clean up this code... any help is much appreciated.
Note: It works just fine, I just think it could be done cleaner.

The result is a stack of dictionaries. the query returns up to
STACK_SIZE ads for a user. The check which i think is very ugly is
putting another contraint saying that all of the ni have to be the
same.

stack = []
rows = self.con.execute(adquerystring,(user,STACK_SIZE)).fetchall()
for row in  rows:
ad = dict()
ad['ni'] = row['ni']
ad['adid'] = row['adid']
ad['rundateid'] = row['rundateid']
ad['rundate'] = row['rundate']
if row['city'] is None:
ad['city'] = 'None'
else:
ad['city'] = row['city']
if row['state'] is None:
ad['state'] = 'None'
else:
ad['state'] = row['state']
ad['status'] = row['status']
try:
if stack[0]['ni'] != ad['ni']:
break;
except IndexError:
pass
stack.append(ad)
--
http://mail.python.org/mailman/listinfo/python-list


Re: where is the PyString_AsString in Python 3.0?

2009-03-06 Thread Benjamin Peterson
BigHand  gmail.com> writes:
> 
> Finally I got the results now. This did take me 10 hours to solve
> this. the docs of 3.0..
> I hope this could help someone else:

> const char *strExcType =  PyBytes_AS_STRING(pyStr);
> Py_XDECREF(str_exc_type);
> Py_XDECREF(pyStr);

You can't Py_DECREF() pyStr while holding on to strExcType because
PyBytes_AS_STRING just yields a reference to the internal contents of the 
object.


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


Re: retrieve traceback in embedded python of Python3.0?

2009-03-06 Thread BigHand
On Mar 7, 11:40 am, BigHand  wrote:
> Guys:
> I have a embedded python in MFC app. to execute a py script of a.py,
> the is only one line in a.py, it "a()" , normally ,excute this script
> file ,you will get a
>  "the exception type is "
> "The exception value is name 'a' is not defined "
>
> Python3.0 with VS2005.
> here is the brief code:
> Py_Initialize();
> PyObject *m, *d, *v;
> m = PyImport_AddModule("__main__");
> d = PyModule_GetDict(m);
> v = PyRun_File(fp, pStr, Py_file_input, d, d);       //~~~the py
> script is a.py
> PyObject *exc_type = NULL, *exc_value = NULL, *exc_tb = NULL;
> PyErr_Fetch(&exc_type, &exc_value, &exc_tb);  //~~~after fetch , the
> exc_type, exc_value, exc_tb are not "NULL"
> PyObject * modTB = PyImport_ImportModule("traceback");
> PyObject* pyUStr = PyUnicode_FromString("format_exception");
> PyObject* listTB = PyObject_CallMethodObjArgs(modTB,  pyUStr,
> exc_type, exc_value, exc_tb, NULL);
>
> in the PyObject_CallMethodObjArgs(modTB,  pyUStr, exc_type, exc_value,
> exc_tb, NULL), I get modTB, pyUStr, exc_type, exc_value, exc_tb are
> not NULL, but the listTB is always NULL, I can retrieve the list...
>
> any body could enlight me?

it's "I can't retrieve the traceback list."
--
http://mail.python.org/mailman/listinfo/python-list


Re: retrieve traceback in embedded python of Python3.0?

2009-03-06 Thread BigHand
On Mar 7, 11:40 am, BigHand  wrote:
> Guys:
> I have a embedded python in MFC app. to execute a py script of a.py,
> the is only one line in a.py, it "a()" , normally ,excute this script
> file ,you will get a
>  "the exception type is "
> "The exception value is name 'a' is not defined "
>
> Python3.0 with VS2005.
> here is the brief code:
> Py_Initialize();
> PyObject *m, *d, *v;
> m = PyImport_AddModule("__main__");
> d = PyModule_GetDict(m);
> v = PyRun_File(fp, pStr, Py_file_input, d, d);       //~~~the py
> script is a.py
> PyObject *exc_type = NULL, *exc_value = NULL, *exc_tb = NULL;
> PyErr_Fetch(&exc_type, &exc_value, &exc_tb);  //~~~after fetch , the
> exc_type, exc_value, exc_tb are not "NULL"
> PyObject * modTB = PyImport_ImportModule("traceback");
> PyObject* pyUStr = PyUnicode_FromString("format_exception");
> PyObject* listTB = PyObject_CallMethodObjArgs(modTB,  pyUStr,
> exc_type, exc_value, exc_tb, NULL);
>
> in the PyObject_CallMethodObjArgs(modTB,  pyUStr, exc_type, exc_value,
> exc_tb, NULL), I get modTB, pyUStr, exc_type, exc_value, exc_tb are
> not NULL, but the listTB is always NULL, I can retrieve the list...
>
> any body could enlight me?

it's "I can't retrieve the trace back list."
--
http://mail.python.org/mailman/listinfo/python-list


retrieve traceback in embedded python of Python3.0?

2009-03-06 Thread BigHand
Guys:
I have a embedded python in MFC app. to execute a py script of a.py,
the is only one line in a.py, it "a()" , normally ,excute this script
file ,you will get a
 "the exception type is "
"The exception value is name 'a' is not defined "


Python3.0 with VS2005.
here is the brief code:
Py_Initialize();
PyObject *m, *d, *v;
m = PyImport_AddModule("__main__");
d = PyModule_GetDict(m);
v = PyRun_File(fp, pStr, Py_file_input, d, d);   //~~~the py
script is a.py
PyObject *exc_type = NULL, *exc_value = NULL, *exc_tb = NULL;
PyErr_Fetch(&exc_type, &exc_value, &exc_tb);  //~~~after fetch , the
exc_type, exc_value, exc_tb are not "NULL"
PyObject * modTB = PyImport_ImportModule("traceback");
PyObject* pyUStr = PyUnicode_FromString("format_exception");
PyObject* listTB = PyObject_CallMethodObjArgs(modTB,  pyUStr,
exc_type, exc_value, exc_tb, NULL);

in the PyObject_CallMethodObjArgs(modTB,  pyUStr, exc_type, exc_value,
exc_tb, NULL), I get modTB, pyUStr, exc_type, exc_value, exc_tb are
not NULL, but the listTB is always NULL, I can retrieve the list...

any body could enlight me?


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


Re: Threading and tkinter

2009-03-06 Thread gert
On Mar 6, 7:42 pm, a...@pythoncraft.com (Aahz) wrote:
> [posted and e-mailed -- please reply to the group]
>
> In article 
> <492d5db9-3681-4ae8-827e-f2a4f66be...@v39g2000yqm.googlegroups.com>,
>
> gert   wrote:
>
> >After reading the docs and seeing a few examples i think this should
> >work ?
>
> This is a bit late, and I don't have time to review your code, but you
> should see a good example here:
>
> http://www.pythoncraft.com/OSCON2001/index.html
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> "All problems in computer science can be solved by another level of    
> indirection."  --Butler Lampson

Witch basically translate into stop being a smart ass and just do
this :)

from tkinter import *

def weegbrug():
with open('com1','r') as f:
 for l in f:
 v.set(l[2:-1])
root.after(500, weegbrug)

root = Tk()
v = StringVar()
v.set("0")
txt = Label(root, textvariable=v, width=800, height=600, bg="yellow",
font=("Helvetica", 300))
txt.pack(expand=YES, fill=BOTH)
root.title("weegbrug")
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (root.winfo_screenwidth(),
root.winfo_screenheight()))
root.after(500, weegbrug)
root.mainloop()
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Daniel Fetchinson
>> Why this hostility? The guy has worked on an interesting piece of
>> software and tries to promote it to people who are most probably
>> interested in programming languages. What's wrong with that?
>
> Because there's no particular reason for it to be in a Python-specific
> forum.

Yes there is, for example I found it useful (I'm interested in dynamic
languages but I'm only subscribed to c.l.p) maybe others too. Gave me
a much needed 5 minutes of recreational reading of his website which
was just about perfect while drinking my coffee during coffee break :)

> The value of a Python-specific forum is directly reduced by the
> amount of off-topic noise that occurs in it.

Yes, but not everything that is off-topic is noise.

> The hostility is because we need to kick the camel's nose of “just
> one clearly off-topic discussion” out of the tent to avoid the whole
> camel coming in.

Are you seriously worried that c.l.p will be overtaken by zealous dao fans?

Cheers,
Daniel


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


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Daniel Fetchinson
 This is to announce the first official release of Dao.

 Dao is a simple yet powerful object-oriented programming language
>>> So, you pimp your language in news groups for other languages?  I see
>>> your off topic post in 3 language groups I frequent, that's not the way
>>> to get interest in your language.
>>
>> Why this hostility?
>
> Why your hostility to people asking questions and making comments and
> statements in response to a boilerplate announcement?
>
>> The guy has worked on an interesting piece of
>> software and tries to promote it to people who are most probably
>> interested in programming languages. What's wrong with that?
>
> There are probably a hundred other 'interesting pieces of software' that
> could be announced here.

There are tons of 'interesting pieces of software' that are actually
announced here. And there is nothing wrong with that.

>  What the OP make no attempt to do was craft a
> post actually directed to this particular group.  Something like 'It has
> the following influences from Python...' or 'Here is how it compares to
> Python...'.  Either would have made it a communication rather than a
> blind broadcast.

A blind broadcast serves a purpose, namely if someone knows nothing
about this language, he/she will get to know that it exists. This is a
useful purpose especially because the probability that people wish to
know about the existence of the OP's new language is quite high (I
suppose) among c.l.p readers. For example they can go to the website
and see how it was influenced by python or how it compares to it.

>  > Some
>> people occasionally ask general computer/linux/IT/etc questions simply
>> because they think that the probability of finding somebody among
>> python list followers who knows the answer (and is willing to share
>> his/her knowledge) is high and since the topic is
>> computer/linux/IT/etc it's not super far from things which are
>> explicitly on topic.
>
> Mostly those are people who have posted Python questions and comments
> before and otherwise are people planning to implement the answer in
> Python.
>
>> No need for any hatred or hostility towards people who write a new
>> programming language,
>
> I did not see any such thing.  The mild hostility was directed at the
> act of blind spamming, which we have had more than enough of.

Well, there are lots of OT postings but in my estimation those that
mention another language generate more hostility than those that
don't. I don't see any reason for this increased hostility relative to
other OT postings, hence I made my remark.

Cheers,
Daniel


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


Re: where is the PyString_AsString in Python 3.0?

2009-03-06 Thread BigHand
On Mar 7, 9:34 am, BigHand  wrote:
> On Mar 7, 3:50 am, Benjamin Peterson  wrote:
>
> > BigHand  gmail.com> writes:
>
> > > > There is no PyString_AsString. Everything
> > >> string is unicode now. (PyUnicode API)
> > > hello,Ben,
> > > could you give me an example? I almost know the
> > > PyUnicode API,but the
> > > docs of 3.0 is too brief for me.
>
> > PyString_FromString -> PyUnicode_FromString
> > PyString_Concat -> PyUnicode_Concat
> > etc...
>
> > To get a char * you have to explicitly encode the string with
> > PyUnicode_AsEncodedString.
>
> thanks Ben!

Finally I got the results now. This did take me 10 hours to solve
this. the docs of 3.0..
I hope this could help someone else:

PyObject *exc_type = NULL, *exc_value = NULL, *exc_tb = NULL;
PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
PyObject* str_exc_type = PyObject_Repr(exc_type); //Now a unicode
object
PyObject* pyStr = PyUnicode_AsEncodedString(str_exc_type, "utf-8",
"Error ~");
const char *strExcType =  PyBytes_AS_STRING(pyStr);
Py_XDECREF(str_exc_type);
Py_XDECREF(pyStr);

Py_XDECREF(exc_type);
Py_XDECREF(exc_value);
Py_XDECREF(exc_tb);


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


Re: Is there a better way of doing this?

2009-03-06 Thread Paul Rubin
"Gabriel Genellina"  writes:
> > for x in population:
> > f = fitness(x)
> > fap += [(f, x)]
> > total += f
> > return sorted(fap, reverse=True), total
> ...
> Environmentally friendly Pythoneers avoid using discardable
> intermediate  envelopes:
> 
>   fap.append((f, x))

I'd probably use:

 fap = list((fitness(x),x) for x in population)
 total = sum(x for x,y in fap)
 return sorted(fap, reverse=True), total
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2009-03-06 Thread Gabriel Genellina

En Fri, 06 Mar 2009 21:31:01 -0200, mattia  escribió:

Thanks, I've found another solution here:  
http://www.obitko.com/tutorials/

genetic-algorithms/selection.php
so here is my implementation:


def get_fap(fitness, population):
fap = []
total = 0
for x in population:
f = fitness(x)
fap += [(f, x)]
total += f
return sorted(fap, reverse=True), total


Imagine you're working with someone side by side. You write a note in a  
piece of paper, put it into an envelope, and hand it to your co-worker. He  
opens the envelope, throws it away, takes the note and files it inside a  
folder right at the end. And you do this over and over. What's wrong in  
this story?


Please save our trees! Don't waste so many envelopes - that's just what  
this line does:


 fap += [(f, x)]

Environmentally friendly Pythoneers avoid using discardable intermediate  
envelopes:


 fap.append((f, x))

Please recycle!

--
Gabriel Genellina

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


image exclude values from resize

2009-03-06 Thread T Kirstine
I've been  downsampling  RGB images using pil, but know I would like to
exclude black 0,0,0 values from the resize calculations.  I was hoping that
applying a alapha mask to black areas and creating RGBA image then
performing the resample would fix the issue but no such luck.

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


Re: create boolean

2009-03-06 Thread Rhodri James

On Fri, 06 Mar 2009 15:34:08 -, Grant Edwards  wrote:


On 2009-03-06, Fencer  wrote:


Hi, I need a boolean b to be true if the variable n is not
None and not an empty list, otherwise b should be false.



I ended up with:



b = n is not None and not not n


I'd do it like this:

  b = (n is not None) and (n != [])


The second comparison isn't actually necessary, since an
empty list is True and a non-empty one False.

  b = (n is not None) and n

Putting the comparison in does make the code slightly less
"magic", though, so it's not a bad idea to do it!


--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: where is the PyString_AsString in Python 3.0?

2009-03-06 Thread BigHand
On Mar 7, 3:50 am, Benjamin Peterson  wrote:
> BigHand  gmail.com> writes:
>
> > > There is no PyString_AsString. Everything
> >> string is unicode now. (PyUnicode API)
> > hello,Ben,
> > could you give me an example? I almost know the
> > PyUnicode API,but the
> > docs of 3.0 is too brief for me.
>
> PyString_FromString -> PyUnicode_FromString
> PyString_Concat -> PyUnicode_Concat
> etc...
>
> To get a char * you have to explicitly encode the string with
> PyUnicode_AsEncodedString.

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


Re: Bizarre import duplication.

2009-03-06 Thread Gabriel Genellina
En Fri, 06 Mar 2009 22:05:53 -0200, Richard Thomas   
escribió:



Say I have a project like this:

./run.py
./package/__init__.py
./package/mod1.py
./package/subpackage/__init__.py
./package/subpackage/mod2.py
./package/subpackage/mod3.py

And suppose that "." and "package" (or their absolute paths) are in
sys.path.


That's a mistake. Never put redundant directories in sys.path. In this  
case, mod1 is reachable as "package.mod1" (from the "." entry in sys.path)  
and also as "mod1" (from the "package" entry). That must not happen -  
module names *must* be unique (here, "module name" means "sequence of  
package names plus the final file name", starting at some entry in  
sys.path)
Usually there is no need (and it's not even convenient) to put a package  
in sys.path -- the directory *containing* the package should be listed  
instead. In this case, it is ".".



Now mod1.py and mod2.py both contain this:
from subpackage import mod3

In this very particular case, the two references to mod3 are separate
initialisations of mod3.py. This can't be the intended behaviour, its
maybe a little contrived but I found myself want to set it up this way
so it can't be outside possibility.


Using a relative import (and enabling absolute imports by default, by  
using: from __future__ import absolute_imports) is somewhat safer, but you  
can still confuse the complicated import machinery if you put redundant  
entries in sys.path


--
Gabriel Genellina

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
Gary Herron wrote:

>>> Newbies: Never use "is" to compare anything.
>>
>> Worse and worse! Now you're actively teaching newbies to write buggy
>> code!
> 
> Nonsense.  Show me "newbie" level code that's buggy with "==" but
> correct with "is".

What's "newbie" level code? What does that even *mean*? There's no sandbox
for newbies to play in -- their code runs in the same environment as code
written by experts. Newbies can import modules written by experts and use
their code: any object, no matter how complex, might find itself imported
and used by a newbie. Sometimes code written by newbies might even find its
way into code used by experts.

But regardless of that, the point is, what's your motivation in giving
advice to newbies? Do you want them to learn correct coding techniques, or
to learn voodoo programming and superstition? If you want them to learn
correct coding, then teach them the difference between identity and
equality. If you want them to believe superstitions, then continue telling
them never to use "is" without qualifications.



-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread skip

Steven> Mutable versus immutable is irrelevant. The complexity of the
Steven> object is irrelevant. The phase of the moon is irrelevant. The
Steven> *only* relevant factor is the programmer's intention:

Which for a new user not familiar with the differing concepts of "is" and
"==" can lead to mistakes.

Steven> If you find it difficult to think of a reason for testing for
Steven> identity, you're right, there aren't many. Since it's rare to
Steven> care about identity, it should be rare to use "is". But in the
Steven> few times you do care about identity, the correct solution is to
Steven> use "is" no matter what sort of object it happens to be. It
Steven> really is that simple.

Right.  Again though, when newcomers conflate the concepts they can deceive
themselves into thinking "is" is just a faster "==".

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Robert Kern

On 2009-03-06 18:29, Paul Rubin wrote:

Steven D'Aprano  writes:

It is never
correct to avoid using "is" when you need to compare for identity.


When is it ever necessary to compare for identity?


Caches of arbitrary objects.

When checking if an object (which may be have an arbitrarily perverse __eq__) is 
None.


Or a specifically constructed sentinel value.

Checking for cycles in a data structure that defines __eq__.

--
Robert Kern

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

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
s...@pobox.com wrote:

> Of course, the more complex the objects you are comparing the
> stronger the recommendation agaist using 'is' to compare two objects.

Why is there so much voodoo advice about "is"? Is object identity really
such a scary concept that people are frightened of it?

Mutable versus immutable is irrelevant. The complexity of the object is
irrelevant. The phase of the moon is irrelevant. The *only* relevant factor
is the programmer's intention:

If you want to test whether two objects have the same value (equality), the
correct way to do it is with "==".

If you want to test whether two objects are actually one and the same
object, that is, they exist at the same memory location (identity), the
correct way to do it is with "is".

If you find it difficult to think of a reason for testing for identity,
you're right, there aren't many. Since it's rare to care about identity, it
should be rare to use "is". But in the few times you do care about
identity, the correct solution is to use "is" no matter what sort of object
it happens to be. It really is that simple.



-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Paul Rubin
Steven D'Aprano  writes:
> It is never
> correct to avoid using "is" when you need to compare for identity.

When is it ever necessary to compare for identity?
--
http://mail.python.org/mailman/listinfo/python-list


Re: uniqueness of temporary files generated by tempfile

2009-03-06 Thread Emile van Sebille

Catherine Moroney wrote:

Are the temporary filenames generated by the tempfile module
guaranteed to be unique?


I suspect this answers your question...

Emile


>>> import tempfile
>>> help(tempfile)
Help on module tempfile:

NAME
tempfile - Temporary files.

FILE
c:\python25\lib\tempfile.py

DESCRIPTION
This module provides generic, low- and high-level interfaces for
creating temporary files and directories.  The interfaces listed
as "safe" just below can be used without fear of race conditions.
Those listed as "unsafe" cannot, and are provided for backward
compatibility only.

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


Re: Asking for prophecy

2009-03-06 Thread Terry Reedy

Stefan Spoettl wrote:
In the pass it was always a good idea to use the newest Python verison 
for starting the development of a new application. First one could 
benefit from the additional features and second one could be sure that 
the community would have been passing during development.
 
Nowadays we have at least three Python versions (2.5, 2.6, 3.0) on our 
machines and - damned! - I really don’t know which version I should use 
for my next development. The Unix-like systems as much as the major part 
of well maintained third party libraries are remaining "penetrantly" on 
2.5. Why the vangard of the community don’t like to use at least 2.6 for 
bridging to the future Python? Is this the mutiny against the empery of 
the BDFL or is the vangard just asking for some more time? If I want to 
attest my personal attachment to the king by using 3.0, what will 
happen? Will I be deserted someday?


It typically takes about a year before *most* 3-rd party libs have been 
converted.  Windows binaries for C extentions tend to be slowest to 
arrive.  Many people routinely skip 2.x.0 and wait to 2.x.1 both to skip 
initial bugs and wait for libraries.  I have no idea if 2.6 conversions 
are slower than usual or not.


3.0 conversion was expected to be a bit slower.  On the other hand, it 
is an opportunity to increase mindshare for libs which do make the 
conversion.


I expect usage of Py3 will increase noticeably when 3.1 comes out in a 
few months with some notable fixes and improvements.


I think there is at least half a chance that 2.7, which should arrive 
with 3.2, will be the last 2.x version.


In the meanwhile, use whichever one meets your needs.  I am currently 
using 3.0, but have 2.5 loaded in case I want to do something that needs 
3rd-party libs before they are available for 3.x.


Terry Jan Reedy

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


Re: Parsing/Crawler Questions - solution

2009-03-06 Thread rounderweget
So, it sounds like your update means that it is related to a specific
url.

I'm curious about this issue myself.  I've often wondered how one
could properly crawl an AJAX-ish site when you're not sure how quickly
the data will be returned after the page has been.

John, your advice has really helped me.  Bruce / anyone else, have you
had any further experience with this type of parsing / crawling?


On Mar 5, 2:50 pm, "bruce"  wrote:
> hi john...
>
> update...
>
> further investigation has revealed that apparently, for some urls/sites, the
> server serves up pages that take awhile to be fetched... this appears to be
> a potential problem, in that it appears that the parsescript never gets
> anything from the python mech/urllib read function.
>
> the curious issue is that i can run a single test script, pointing to the
> url, and after a bit of time.. the resulting content is fetched/downloaded
> correctly. by the way, i can get the same results in my test browsing
> environment, if i start it with only a subset of the urs that i've been
> using to test the app.
>
> hmm... might be a resource issue, a timing issue,.. or something else...
> hmmm...
>
> thanks
>
> again the problem i'm facing really has nothing to do with a specific
> url... the app i have for the usc site works...
>
> but for any number of reasons... you might get different results when
> running the app..
> -the server could be screwed up..
> -data might be cached
> -data might be changed, and not updated..
> -actual app problems...
> -networking issues...
> -memory corruption issues...
> -process constraint issues..
> -web server overload..
> -etc...
>
> the assumption that most people appear to make is that if you create a
> parser, and run and test it once.. then if it gets you the data, it's
> working.. when you run the same app.. 100s of times, and you're slamming the
> webserver... then you realize that that's a vastly different animal than
> simply running a snigle query a few times...
>
> so.. nope, i'm not running the app and getting data from a dynamic page that
> hasn't finished uploading/creating the content..
>
> but what my analysis is showing, not only for the usc, but for others as
> well.. is that there might be differences in what gets returned...
>
> which is where a smoothing algorithmic approach appears to be workable..
>
> i've been starting to test this approach, and it actually might have a
> chance of working...
>
> so.. as i've stated a number of times.. focusing on a specific url isn't the
> issue.. the larger issue is how you can
> programatically/algorithmically/automatically, be reasonably ensured that
> what you have is exactly what's on the site...
>
> ain't screen scraping fun!!!
>
> -Original Message-
> From: python-list-bounces+bedouglas=earthlink@python.org
>
> [mailto:python-list-bounces+bedouglas=earthlink@python.org]on Behalf
> Of John Nagle
> Sent: Thursday, March 05, 2009 10:54 AM
> To: python-l...@python.org
> Subject: Re: Parsing/Crawler Questions - solution
>
> Philip Semanchuk wrote:
> > On Mar 5, 2009, at 12:31 PM, bruce wrote:
>
> >> hi..
>
> >> the url i'm focusing on is irrelevant to the issue i'm trying to solve at
> >> this time.
>
> > Not if we're to understand the situation you're trying to describe. From
> > what I can tell, you're saying that the target site displays different
> > results each time your crawler visits it. It's as if e.g. the site knows
> > about 100 courses but only displays 80 randomly chosen ones to each
> > visitor. If that's the case, then it is truly bizarre.
>
>      Agreed.  The course list isn't changing that rapidly.
>
>      I suspect the original poster is doing something like reading the DOM
> of a dynamic page while the page is still updating, running a browser
> in a subprocess.  Is that right?
>
>      I've had to deal with that in Javascript.  My AdRater browser plug-in
> (http://www.sitetruth.com/downloads) looks at Google-served ads and
> rates the advertisers.   There, I have to watch for page-change events
> and update the annotations I'm adding to ads.
>
>      But you don't need to work that hard here. The USC site is actually
> querying a server which provides the requested data in JSON format.  See
>
>        http://web-app.usc.edu/soc/dev/scripts/soc.js
>
> Reverse-engineer that and you'll be able to get the underlying data.
> (It's an amusing script; many little fixes to data items are performed,
> something that should have been done at the database front end.)
>
> The way to get USC class data is this:
>
> 1.  Start here: "http://web-app.usc.edu/soc/term_20091.html";
> 2.  Examine all the department pages under that page.
> 3.  On each page, look for the value of "coursesrc", like this:
>         var coursesrc = '/ws/soc/api/classes/aest/20091'
> 4.  For each "coursesrc" value found, construct a URL like this:
>        http://web-app.usc.edu/ws/soc/api/classes/aest/20091
> 5.  Read that URL.  This will return the departmen

Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Ben Finney
Daniel Fetchinson  writes:

> Why this hostility? The guy has worked on an interesting piece of
> software and tries to promote it to people who are most probably
> interested in programming languages. What's wrong with that?

Because there's no particular reason for it to be in a Python-specific
forum. The value of a Python-specific forum is directly reduced by the
amount of off-topic noise that occurs in it.

The hostility is because we need to kick the camel's nose of “just
one clearly off-topic discussion” out of the tent to avoid the whole
camel coming in.

-- 
 \“I fly Air Bizarre. You buy a combination one-way round-trip |
  `\ticket. Leave any Monday, and they bring you back the previous |
_o__) Friday. That way you still have the weekend.” —Steven Wright |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Bizarre import duplication.

2009-03-06 Thread Richard Thomas
Say I have a project like this:

./run.py
./package/__init__.py
./package/mod1.py
./package/subpackage/__init__.py
./package/subpackage/mod2.py
./package/subpackage/mod3.py

And suppose that "." and "package" (or their absolute paths) are in
sys.path.

Now mod1.py and mod2.py both contain this:
from subpackage import mod3

In this very particular case, the two references to mod3 are separate
initialisations of mod3.py. This can't be the intended behaviour, its
maybe a little contrived but I found myself want to set it up this way
so it can't be outside possibility.

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Carl Banks
On Mar 6, 12:23 pm, Gary Herron  wrote:
> Robert Kern wrote:
> > On 2009-03-06 13:46, Gary Herron wrote:
> >> Emanuele D'Arrigo wrote:
> >>> Hi everybody,
>
> >>> while testing a module today I stumbled on something that I can work
> >>> around but I don't quite understand.
>
> >> *Do NOT use "is" to compare immutable types.* **Ever! **
>
> > Well, "foo is None" is actually recommended practice
>
> But since newbies are always falling into this trap, it is still a good
> rule to say:
>
>   Newbies:  Never use "is" to compare immutable types.

No it isn't, it's asinine advice that's not even a simpllified truth,
it's just a lie.

Newbies who don't understand the difference between "==" and "is"
should not be using "is", for any object, immutable or mutable, aside
from None (which, whether you like it or not, is idomatic Python).

Everyone who's learned the difference between equality and same
identity, including experts, should be using "is" only to test if some
object is the same object they created themselves, or is an object
guaranteed by a library or the langauge to never change, irrespective
of whether the object is mutable or not.

At no point on the learning curve is the distinction of when to use
"is" or not ever mutability.


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


uniqueness of temporary files generated by tempfile

2009-03-06 Thread Catherine Moroney

Are the temporary filenames generated by the tempfile module
guaranteed to be unique?

I have a need to generate temporary files within an application,
and I will have many instances of this application running as a
sub-process (so I can submit them to a batch queue).  Is there
any danger of my different sub-processes accidentally generating
the same filename, or does tempfile check for the existence of
a similarly-named file before generating a filename?

What's the recommended way of generating temporary filenames
that are guaranteed to be unique even with multiple processes
running simultaneously?

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Gabriel Genellina
En Fri, 06 Mar 2009 19:31:02 -0200, Emanuele D'Arrigo   
escribió:



a = "a"
b = "a"
a is b

True


a = "/a"  <- same as above, except the forward slashes!
b = "/a"  <- same as above, except the forward slashes!
a is b

False

So, it appears that in the first case a and b are names to the same
string object, while in the second case they are to two separate
objects. Why? What's so special about the forward slash that cause the
two "/a" strings to create two separate objects? Is this an
implementation-specific issue?


With all the answers you got, I hope you now understand that you put the  
question backwards: it's not "why aren't a and b the very same object in  
the second case?" but "why are they the same object in the first case?".


Two separate expressions, involving two separate literals, don't *have* to  
evaluate as the same object. Only because strings are immutable the  
interpreter *may* choose to re-use the same string. But Python would still  
be Python even if all those strings were separate objects (although it  
would perform a lot slower!)


--
Gabriel Genellina

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


Re: searching for an easy library to create OpenOffice spreadsheets

2009-03-06 Thread Terry Reedy

Krishnakant wrote:

Hello all,
I am looking out for a python library which does the followingg.
1, create and manipulate openoffice spreadsheets.


OpenOffice, by default, creates ODF -- Open Document Format -- documents 
as zipped xml subdocuments.  Ooo is just one of many programs that work 
with them.  One can access the actual xml with any decent zip program, 
such as 7zip.



2, allow for cell formatting including merging cells.
3, allow for colouring cells and formatting data as bold italics etc.
4, alignment of data should be possible.
I looked at ooolib but did not find a method for merging cells.



any ideas?


odf2py?  Have not used it yet.  To get an idea of how to do what you 
want to do, create a simple spreadsheet with merged and formatted cells 
with OOoCalc and then look at the resulting xml rendition.



tjr

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


Re: How to replace the two last digits from an xml file?

2009-03-06 Thread odeits
On Mar 6, 3:31 pm, odeits  wrote:
> On Mar 6, 11:53 am, awel  wrote:
>
>
>
> > Hi,
>
> > I am trying to get a value from an xml file, increment it by 1,
> > replace by the new value and write another xml with the new value
> > inside.
>
> > I have found this code to get the line and it works but I have to do
> > everything manualy:
>
> > import re
> > lines = open("c:\\File1.xml").readlines()
> > for i in range(len(lines)):
> >     if re.search('national.number', lines[i]):
> >         lines[i] = lines[i].replace
> > ('01aaa02','01aaa03')
> > open("File2.xml","w").writelines(lines)
>
> > The goal I am trying to reach is to create 30 different xml.
>
> > Could someone help me?
>
> > Thanks
> > Al
>
> I would look into actually using an xml parser like lxml or the built
> in elementTree. You might run into some problems later on with the
> regex matching something unintended. Having said that..
>
> If you want to stick to regex i would pull out the number using a
> group, convert the number to a python type, increment then do the
> replace.

having dug a little deeper myself into the regular expressions in
python and grouping i stumbled onto this
http://www.amk.ca/python/howto/regex/regex.html#SECTION00052

Right above section 6. Common Problems there is an example of how to
change decimal numbers to hex... with a little tweek i believe it will
do exactly what you want.

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


Re: Reading Special Administration Console (SAC) in python

2009-03-06 Thread Emile van Sebille

krishnakishore.nakarika...@gmail.com wrote:


I want to read the Special Administration Console (SAC) output spew
using python. Is it possible for me? 


It looks like that's just serial port I/O.  If that doesn't get you 
going in the right direction it'll be a tough road...


Emile

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


Re: Should I use stackless python or threads?

2009-03-06 Thread Minesh Patel
On Fri, Mar 6, 2009 at 3:16 PM, Jean-Paul Calderone  wrote:
> On Fri, 6 Mar 2009 14:50:51 -0800, Minesh Patel  wrote:
>>
>> I am trying to figure out the best approach to solve this problem:
>>
>> I want to poll various directories(can be run in the main thread).
>> Once I notice a file has been added to any directory, I grab a lock,
>> spawn a thread to go perform the necessary actions, and then release
>> the lock.
>
> That's not a description of a problem.  That's a description of a potential
> solution.  What problem are you trying to solve?
>

I have a build system that is outputting various forms of
installations in a particular directory structure, e.g. /pxe-installs,
/iso-install, /dd-installs, etc...

I need to monitor each directory for the latest install, take it and
go perform some tests on a specific machine. I would like these
testing tasks to run concurrently for the obvious reasons.

Thanks again for the help,
Minesh
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to replace the two last digits from an xml file?

2009-03-06 Thread odeits
On Mar 6, 11:53 am, awel  wrote:
> Hi,
>
> I am trying to get a value from an xml file, increment it by 1,
> replace by the new value and write another xml with the new value
> inside.
>
> I have found this code to get the line and it works but I have to do
> everything manualy:
>
> import re
> lines = open("c:\\File1.xml").readlines()
> for i in range(len(lines)):
>     if re.search('national.number', lines[i]):
>         lines[i] = lines[i].replace
> ('01aaa02','01aaa03')
> open("File2.xml","w").writelines(lines)
>
> The goal I am trying to reach is to create 30 different xml.
>
> Could someone help me?
>
> Thanks
> Al

I would look into actually using an xml parser like lxml or the built
in elementTree. You might run into some problems later on with the
regex matching something unintended. Having said that..

If you want to stick to regex i would pull out the number using a
group, convert the number to a python type, increment then do the
replace.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2009-03-06 Thread mattia
Il Fri, 06 Mar 2009 14:13:47 -0800, Scott David Daniels ha scritto:

> mattia wrote:
>> Here is my last shot, where I get rid of all the old intermediate
>> functions:
>> 
>> def selection(fitness, population):
>> lp = len(population)
>> roulette_wheel = []
>> for x in population:
>> roulette_wheel += [x]*fitness(x)
>> selected_population = [[]]*lp
>> selected_population[:2] = sorted(population, key=fitness,
>> reverse=True)[:2]
>> selected_population[2:] = [choice(roulette_wheel) for _ in range
>> (lp-2)]
> Try something like this to choose likely couples:
> 
>  import random
>  import bisect
> 
>  def choose_pairs(fitness_population, decider=random):
>  '''Pick and yield pairs weighted by fitness for crossing.
> 
>  We assume weighted_population has fitness already calculated.
>  decide is a parameter to allow testing. '''
>  total = 0
>  cumulative = []
>  candidates = []
>  for fitness, individual in set(fitness_population):
>  # calculate total weights, extract real candidates if
>  fitness > 0:
>  total += fitness
>  cumulative.append(total)
>  candidates.append(individual)
>  assert len(candidates) > 1
>  while True:
>  # pick a candidate by weight
>  c0 = decider.random() * total
>  first = bisect.bisect_left(cumulative, c0) if first:
>  weighting = cumulative[first] - cumulative[first - 1]
>  else:
>  weighting = cumulative[0]
>  # pick another distinct candidate by fitness c1 = choice =
>  decider.random() * (total - weighting) if choice >=
>  cumulative[first] - weighting:
>  choice += weight # adjust to avoid selecting first
>  second = bisect.bisect_left(cumulative, choice) yield
>  candidates[first], candidates[second]
> 
> --Scott David Daniels
> scott.dani...@acm.org

Thanks, I've found another solution here: http://www.obitko.com/tutorials/
genetic-algorithms/selection.php
so here is my implementation:

def create_chromosome(min, max, length):
return [randint(min, max) for i in range(length)]

def create_population(nelem, min, max, length):
# preconditions: nelem > 1 and nelem is even
if not nelem > 1:
nelem = 2
if not nelem%2 == 0:
print("The population must have an even number of elements. 
Correcting...")
nelem += 1  
return [create_chromosome(min, max, length) for i in range(nelem)]

def get_fap(fitness, population):
fap = []
total = 0
for x in population:
f = fitness(x)
fap += [(f, x)]
total += f
return sorted(fap, reverse=True), total

def my_rw():
list, tot = get_fap(sum, pop)
r = randint(0, tot-1)
i = 0
print(r)
for f, e in list:
i += f
print(i)
if i > r:
return e
return [] # never reached

if __name__ == "__main__":
pop = create_population(5, 0, 1, 10)
# selection_mat(sum, pop)
#print(rw(sum, pop))
list, tot = get_fap(sum, pop)
print(list)
print(tot)
for i in range(6):
print(my_rw())
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Terry Reedy

Daniel Fetchinson wrote:

This is to announce the first official release of Dao.

Dao is a simple yet powerful object-oriented programming language

So, you pimp your language in news groups for other languages?  I see
your off topic post in 3 language groups I frequent, that's not the way
to get interest in your language.


Why this hostility?


Why your hostility to people asking questions and making comments and 
statements in response to a boilerplate announcement?



The guy has worked on an interesting piece of
software and tries to promote it to people who are most probably
interested in programming languages. What's wrong with that? 


There are probably a hundred other 'interesting pieces of software' that 
could be announced here.  What the OP make no attempt to do was craft a 
post actually directed to this particular group.  Something like 'It has 
the following influences from Python...' or 'Here is how it compares to 
Python...'.  Either would have made it a communication rather than a 
blind broadcast.


> Some

people occasionally ask general computer/linux/IT/etc questions simply
because they think that the probability of finding somebody among
python list followers who knows the answer (and is willing to share
his/her knowledge) is high and since the topic is
computer/linux/IT/etc it's not super far from things which are
explicitly on topic.


Mostly those are people who have posted Python questions and comments 
before and otherwise are people planning to implement the answer in 
Python.



No need for any hatred or hostility towards people who write a new
programming language,


I did not see any such thing.  The mild hostility was directed at the 
act of blind spamming, which we have had more than enough of.


Terry

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


Re: Should I use stackless python or threads?

2009-03-06 Thread Jean-Paul Calderone

On Fri, 6 Mar 2009 14:50:51 -0800, Minesh Patel  wrote:

I am trying to figure out the best approach to solve this problem:

I want to poll various directories(can be run in the main thread).
Once I notice a file has been added to any directory, I grab a lock,
spawn a thread to go perform the necessary actions, and then release
the lock.


That's not a description of a problem.  That's a description of a 
potential solution.  What problem are you trying to solve?




--
Thanks for the help,
Minesh Patel
--
http://mail.python.org/mailman/listinfo/python-list


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


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread skip

Limin> Honest to say, there is no solid connection between Dao and
Limin> Python.  It's just that I had received some good suggestions and
Limin> comments from these groups when I made a few previous
Limin> announcements in these groups.  So I guessed somebody might be
Limin> interested in Dao, and thought it might be a good idea to
Limin> announce it here again.

Saying just that in your announcement would have been enough, in my opinion
to establish the connection.  It's just that there was no mention of Python
at all in your announcement.  So I asked.

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


Re: "/a" is not "/a" ?

2009-03-06 Thread skip

Gary> *Do NOT use "is" to compare immutable types.* **Ever! **

The obvious followup question is then, "when is it ok to use 'is'?"

Robert> Well, "foo is None" is actually recommended practice

Indeed.  It does have some (generally small) performance ramifications as
well.  Two trivial one-line examples:

% python -m timeit -s 'x = None' 'x is None'
1000 loops, best of 3: 0.065 usec per loop
% python -m timeit -s 'x = None' 'x == None'
1000 loops, best of 3: 0.121 usec per loop
% python -m timeit -s 'x = object(); y = object()' 'x == y'
1000 loops, best of 3: 0.154 usec per loop
% python -m timeit -s 'x = object(); y = object()' 'x is y'
1000 loops, best of 3: 0.0646 usec per loop

I imagine the distinction grows if you implement a class with __eq__ or
__cmp__ methods, but that would make the examples greater than one line
long.  Of course, the more complex the objects you are comparing the
stronger the recommendation agaist using 'is' to compare two objects.

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Gary Herron

Emanuele D'Arrigo wrote:

On 6 Mar, 19:46, Gary Herron  wrote:
  

It is an implementation choice (usually driven by efficiency considerations) to 
choose when two strings with the same value are stored in memory once or twice. 
 In order for Python to recognize when a newly created string has the same 
value as an already existing string, and so use the already existing value, it 
would need to search *every* existing string whenever a new string is created.  
Clearly that's not going to be efficient.  However, the C implementation of 
Python does a limited version of such a thing -- at least with strings of 
length 1.



Gary, thanks for your reply: your explanation does pretty much answer
my question. One thing I can add however is that it really seems that
non-alphanumeric characters such as the forward slash make the
difference, not just the number of characters. I.e.

  

a = "aaa"
b = "aaa"
a is b


True
  

a = "/aaa"
b = "/aaa"
a is b


False

I just find it peculiar more than a nuisance, but I'll go to the
blackboard and write 100 times "never compare the identities of two
immutables". Thank you all!
  


Unless you are *trying* to discern something about the implementation 
and its attempt at efficiencies.  Here's several more interesting example:


>>> 101 is 100+1
True
>>> 1001 is 1000+1
False

>>> 10*'a' is 5*'aa'
True
>>> 100*'a' is 50*'aa'
False


Gary Herron



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


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


Should I use stackless python or threads?

2009-03-06 Thread Minesh Patel
I am trying to figure out the best approach to solve this problem:

I want to poll various directories(can be run in the main thread).
Once I notice a file has been added to any directory, I grab a lock,
spawn a thread to go perform the necessary actions, and then release
the lock.

-- 
Thanks for the help,
Minesh Patel
--
http://mail.python.org/mailman/listinfo/python-list


Re: "/a" is not "/a" ?

2009-03-06 Thread Martin v. Löwis
> So, it appears that in the first case a and b are names to the same
> string object, while in the second case they are to two separate
> objects. Why?

This question is ambiguous:
a) Why does the Python interpreter behave this way?
   (i.e. what specific algorithm produces this result?)
or
b) Why was the interpreter written to behave this way?
   (i.e. what is the rationale for that algorithm?)

For a), the answer is in Object/codeobject.c:

/* Intern selected string constants */
for (i = PyTuple_Size(consts); --i >= 0; ) {
PyObject *v = PyTuple_GetItem(consts, i);
if (!PyString_Check(v))
continue;
if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
continue;
PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
}

So it interns all strings which only consist of name
characters.

For b), the rationale is that such string literals
in source code are often used to denote names, e.g.
for getattr() calls and the like. As all names are interned,
name-like strings get interned also.

> What's so special about the forward slash that cause the
> two "/a" strings to create two separate objects?

See above.

> Is this an implementation-specific issue?

Yes, see above.

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Gary Herron

Steven D'Aprano wrote:

Gary Herron wrote:

  

Robert Kern wrote:


...
  

Use "is" when you really need to compare by object identity and not
value.
  

But that definition is the *source* of the trouble.  It is *completely*
meaningless to newbies.   Until one has experience in programming in
general and experience in Python in particular, the difference between
"object identity" and "value" is a mystery.



Then teach them the difference, rather than give them bogus advice.


  

So in order to lead newbies away from this *very* common trap they often
fall into, it is still a valid rule to say

Newbies: Never use "is" to compare immutable types.



Look in the standard library, and you will see dozens of cases of
first-quality code breaking your "valid" rule.

Your rule is not valid. A better rule might be:

Never use "is" to compare equality.

Or even:

Never use "is" unless you know the difference between identity and equality.

Or even:

Only use "is" on Tuesdays.

At least that last rule is occasionally right (in the same way a stopped
clock is right twice a day), while your rule is *always* wrong. It is never
correct to avoid using "is" when you need to compare for identity.

  

of even better

Newbies: Never use "is" to compare anything.



Worse and worse! Now you're actively teaching newbies to write buggy code!
  


Nonsense.  Show me "newbie" level code that's buggy with "==" but 
correct with "is". 


However, I do like your restatement of the rule this way:
   Never use "is" unless you know the difference between identity and 
equality.
That warns newbies away from the usual pitfall, and (perhaps) won't 
offend those

who seem to forget what "newbie" means.

Gary Herron







  


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


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Limin Fu

> i agree it's not clear how this is related to python (although i can see
> the influence), but it does look like a nice language.

thanks.

>
> one thing i was surprised to find missing was that the discussion of types
> doesn't include classes (the discussion of macros doesn't include types,

Actually the documentation about types does not mean to explain the
types in a systematic way. It just tries to explain how to practically
use them implicitly and explicitly, and to point out where one should
pay attention. Classes surely should be discussed, but it didn't come
into my mind when I prepared the documentation. It will be discussed
when I update the document.

> but that is more understandable).  i am wondering if you have hidden
> problems related to co and contra variance of types (like in java
> generics).

I have paid attention to the variance of types in some situations, but
I am not very sure if it is without problems. Until now, I still feel
there are still many things to be improved in the typing system. It
would not be surprising if there are hidden problems regarding this.


>
> also, why is "@" needed as well as yield?  in python, the presence of
> yield makes "@" implicit (i think).

You are right. I will change this. Thank you for pointing out this.

I am glad that, every time I announced the language in the python
mailing list, I received good comments and suggestions more often than
in other mailing lists and groups, that's why python mailing list is
one of the first places coming into my mind when I plan for an
announcement of Dao;)


>
> andrew
>
> Limin Fu wrote:
> > Hi,
>
> > This is to announce the first official release of Dao.
>
>

--
Limin Fu

http://www.daovm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: qt, gtk, wx for py3 ?

2009-03-06 Thread Peter Billam
On 2009-03-03, Mike Driscoll  wrote:
> It should be noted that the port for 3.0 hasn't started yet for
> wxPython and I'm not seeing anything about a port for PyQt either
> on their website.

On 2009-03-05, Peter Billam  wrote:
> I mailed riverbankcomputing about PyQt for Py3; Phil Thompson replied
> > The next release of PyQt is planned for the end of this month.
> > It *might* make it to that release.
> which, *if* it happens, is not so far away.
> But that still leaves Gtk and Wx...

In the Gtk front, Johan Dahlin of gnome.org points me to:
  http://bugzilla.gnome.org/show_bug.cgi?id=566641
which looks promising...

Regards,  Peter

-- 
Peter Billam   www.pjb.com.auwww.pjb.com.au/comp/contact.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Daniel Fetchinson
>> This is to announce the first official release of Dao.
>>
>> Dao is a simple yet powerful object-oriented programming language
>
> So, you pimp your language in news groups for other languages?  I see
> your off topic post in 3 language groups I frequent, that's not the way
> to get interest in your language.

Why this hostility? The guy has worked on an interesting piece of
software and tries to promote it to people who are most probably
interested in programming languages. What's wrong with that? Some
people occasionally ask general computer/linux/IT/etc questions simply
because they think that the probability of finding somebody among
python list followers who knows the answer (and is willing to share
his/her knowledge) is high and since the topic is
computer/linux/IT/etc it's not super far from things which are
explicitly on topic.

No need for any hatred or hostility towards people who write a new
programming language, I bet many people on this list are interested in
this kind of stuff.

Cheers,
Daniel

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


Re: Is there a better way of doing this?

2009-03-06 Thread mattia
Il Fri, 06 Mar 2009 18:46:44 -0300, andrew cooke ha scritto:

> i have not been following this discussion in detail, so someone may have
> already explained this, but it should not be necessary to actually
> construct the roulette wheel to select values from it.  what you are
> doing is selecting from a list where the there are different
> probabilities of selecting different entries.  i am pretty sure that can
> be done more efficiently than by constructing a new list with many more
> entries whose aim is to simulate that (which is what the roulette wheel
> seems to be in your code, if i have understood correctly).
> 
> more precisely, i think you can adapt the trick used to select a line at
> random from a file by scanning the file just once.
> 
> sorry if i have misunderstood,
> andrew

Well, I believe that using the right distribution I can for sure find a 
better way for doing the roulette wheel selection. When I'll have enough 
time I'll pick up my statistics book.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2009-03-06 Thread Scott David Daniels

mattia wrote:
Here is my last shot, where I get rid of all the old intermediate 
functions:


def selection(fitness, population):
lp = len(population)
roulette_wheel = []
for x in population:
roulette_wheel += [x]*fitness(x)
selected_population = [[]]*lp
selected_population[:2] = sorted(population, key=fitness, 
reverse=True)[:2]

selected_population[2:] = [choice(roulette_wheel) for _ in range
(lp-2)]

Try something like this to choose likely couples:

import random
import bisect

def choose_pairs(fitness_population, decider=random):
'''Pick and yield pairs weighted by fitness for crossing.

We assume weighted_population has fitness already calculated.
decide is a parameter to allow testing.
'''
total = 0
cumulative = []
candidates = []
for fitness, individual in set(fitness_population):
# calculate total weights, extract real candidates
if fitness > 0:
total += fitness
cumulative.append(total)
candidates.append(individual)
assert len(candidates) > 1
while True:
# pick a candidate by weight
c0 = decider.random() * total
first = bisect.bisect_left(cumulative, c0)
if first:
weighting = cumulative[first] - cumulative[first - 1]
else:
weighting = cumulative[0]
# pick another distinct candidate by fitness
c1 = choice = decider.random() * (total - weighting)
if choice >= cumulative[first] - weighting:
choice += weight # adjust to avoid selecting first
second = bisect.bisect_left(cumulative, choice)
yield candidates[first], candidates[second]

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


doctest + shelve question

2009-03-06 Thread Sebastian Bartos
Hello list,

I have a question. I'm writing a simple object serialization module
using shelve to write arbitrary objects to a file (M.py). Now I have the
problem, that if I create a simple object in the doctest documentation
file M.txt like this:

>>> class tdata(object):
... def __init__(self, name):
... self.name = name
>>> tinst = tdata(u'foo')

and then run it with my module M:

>>> import M
>>> foo = M.serialize('/tmp/foo', tinst.name, tinst)

which calls:

class serialize(object):
def __init__(self, path, key, data):
db = shelve.open(path)
db[key.encode('utf-8')] = data
db.close()

then I get the following problem:

Failed example:
foo = M.serialize('/tmp/foo', tinst)
Exception raised:
Traceback (most recent call last):
  File "/usr/lib/python2.5/doctest.py", line 1228, in __run
compileflags, 1) in test.globs
...
  File "/usr/lib/python2.5/shelve.py", line 123, in __setitem__
p.dump(value)
PicklingError: Can't pickle : attribute lookup
__builtin__.tdata failed


If I do the same in the interactive interpreter, then it works fine.

Now, as I want to test an arbitrary data class, the doctest file is the
place to put the simple tdata class, but as far as I traced the problem,
it uses it's own namespace or something, and so does not work.

I'd like to keep a consistent doctest documentation here and not spawn
my project with additional test modules or similar.

Any idea on how I can make it work like as if it would be called from
the interactive interpreter? The documentation and Google were not too
helpful.

ps. Sys: Linux, Python: 2.5.2

thanks

-- 
Sebastian Bartos, 
keyserevr: pgp.mit.edu


signature.asc
Description: This is a digitally signed message part
--
http://mail.python.org/mailman/listinfo/python-list


Re: "/a" is not "/a" ?

2009-03-06 Thread Christian Heimes
Emanuele D'Arrigo wrote:
> So, it appears that in the first case a and b are names to the same
> string object, while in the second case they are to two separate
> objects. Why? What's so special about the forward slash that cause the
> two "/a" strings to create two separate objects? Is this an
> implementation-specific issue?

Python special cases certain objects like str with one element or small
ints from -10 to +256 for performance reasons. It's version and
implementation specific and may change in the future. Do NOT rely on it!
Christian

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


Re: how to prevent python import from looking into the current directory

2009-03-06 Thread TP
Benjamin Peterson wrote:

> While the solutions given by others in this thread will work, I think it
> is best policy to not name your own modules after stdlib ones. When I see
> "os" referenced in code, I assume it is the stdlib one, and don't want to
> be confused by the presence of your own module.

Yes, I have finally chosen this alternative: things are much simpler like
this.
Thanks

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2009-03-06 Thread andrew cooke

i have not been following this discussion in detail, so someone may have
already explained this, but it should not be necessary to actually
construct the roulette wheel to select values from it.  what you are doing
is selecting from a list where the there are different probabilities of
selecting different entries.  i am pretty sure that can be done more
efficiently than by constructing a new list with many more entries whose
aim is to simulate that (which is what the roulette wheel seems to be in
your code, if i have understood correctly).

more precisely, i think you can adapt the trick used to select a line at
random from a file by scanning the file just once.

sorry if i have misunderstood,
andrew


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


Re: "/a" is not "/a" ?

2009-03-06 Thread Emanuele D'Arrigo
On 6 Mar, 19:46, Gary Herron  wrote:
> It is an implementation choice (usually driven by efficiency considerations) 
> to choose when two strings with the same value are stored in memory once or 
> twice.  In order for Python to recognize when a newly created string has the 
> same value as an already existing string, and so use the already existing 
> value, it would need to search *every* existing string whenever a new string 
> is created.  Clearly that's not going to be efficient.  However, the C 
> implementation of Python does a limited version of such a thing -- at least 
> with strings of length 1.

Gary, thanks for your reply: your explanation does pretty much answer
my question. One thing I can add however is that it really seems that
non-alphanumeric characters such as the forward slash make the
difference, not just the number of characters. I.e.

>>> a = "aaa"
>>> b = "aaa"
>>> a is b
True
>>> a = "/aaa"
>>> b = "/aaa"
>>> a is b
False

I just find it peculiar more than a nuisance, but I'll go to the
blackboard and write 100 times "never compare the identities of two
immutables". Thank you all!

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


Re: Is there a better way of doing this?

2009-03-06 Thread mattia
Il Fri, 06 Mar 2009 22:28:00 +0100, Peter Otten ha scritto:

> mattia wrote:
> 
>> Il Fri, 06 Mar 2009 14:06:14 +0100, Peter Otten ha scritto:
>> 
>>> mattia wrote:
>>> 
 Hi, I'm new to python, and as the title says, can I improve this
 snippet (readability, speed, tricks):
 
 def get_fitness_and_population(fitness, population):
 return [(fitness(x), x) for x in population]
 
 def selection(fitness, population):
 '''
 Select the parent chromosomes from a population according to
 their fitness (the better fitness, the bigger chance to be
 selected) ''' selected_population = []
 fap = get_fitness_and_population(fitness, population) pop_len =
 len(population)
 # elitism (it prevents a loss of the best found solution) # take
 the only 2 best solutions
 elite_population = sorted(fap)
 selected_population += [elite_population[pop_len-1][1]] +
 [elite_population[pop_len-2][1]]
 # go on with the rest of the elements for i in range(pop_len-2):
 # do something
>>> 
>>> def selection1(fitness, population, N=2):
>>> rest = sorted(population, key=fitness, reverse=True) best =
>>> rest[:N] del rest[:N]
>>> # work with best and rest
>>> 
>>> 
>>> def selection2(fitness, population, N=2):
>>> decorated = [(-fitness(p), p) for p in population]
>>> heapq.heapify(decorated)
>>> 
>>> best = [heapq.heappop(decorated)[1] for _ in range(N)] rest = [p
>>> for f, p in decorated]
>>> # work with best and rest
>>> 
>>> Both implementations assume that you are no longer interested in the
>>> individuals' fitness once you have partitioned the population in two
>>> groups.
>>> 
>>> In theory the second is more efficient for "small" N and "large"
>>> populations.
>>> 
>>> Peter
>> 
>> Ok, but the fact is that I save the best individuals of the current
>> population, than I'll have to choose the others elements of the new
>> population (than will be N-2) in a random way. The common way is using
>> a roulette wheel selection (based on the fitness of the individuals, if
>> the total fitness is 200, and one individual has a fitness of 10, that
>> this individual will have a 0.05 probability to be selected to form the
>> new population). So in the selection of the best solution I have to use
>> the fitness in order to get the best individual, the last individual
>> use the fitness to have a chance to be selected. Obviously the old
>> population anf the new population must have the same number of
>> individuals.
> 
> You're right, it was a bad idea.
> 
> Peter

Here is my last shot, where I get rid of all the old intermediate 
functions:

def selection(fitness, population):
lp = len(population)
roulette_wheel = []
for x in population:
roulette_wheel += [x]*fitness(x)
selected_population = [[]]*lp
selected_population[:2] = sorted(population, key=fitness, 
reverse=True)[:2]
selected_population[2:] = [choice(roulette_wheel) for _ in range
(lp-2)]
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to prevent python import from looking into the current directory

2009-03-06 Thread Benjamin Peterson
TP  Paralleles.invalid> writes:

> 
> Hi everybody,
> 
> I would like to prevent the loading of modules in the current directory.
> For example, if I have a personal module in the current directory
> named "os", when I do "import os", I would like Python to import os
> standard module, not my personal module of the current directory.
> Is this possible?

While the solutions given by others in this thread will work, I think it is best
policy to not name your own modules after stdlib ones. When I see "os"
referenced in code, I assume it is the stdlib one, and don't want to be confused
by the presence of your own module.


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


Re: "/a" is not "/a" ?

2009-03-06 Thread Emanuele D'Arrigo
Thank you everybody for the contributions and sorry if I reawoke the
recurring "is vs ==" issue.  I -think- I understand how Python's
object model works, but clearly I'm still missing something. Let me
reiterate my original example without the distracting aspect of the
"==" comparisons and the four variables:

>>> a = "a"
>>> b = "a"
>>> a is b
True

>>> a = "/a"  <- same as above, except the forward slashes!
>>> b = "/a"  <- same as above, except the forward slashes!
>>> a is b
False

So, it appears that in the first case a and b are names to the same
string object, while in the second case they are to two separate
objects. Why? What's so special about the forward slash that cause the
two "/a" strings to create two separate objects? Is this an
implementation-specific issue?

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


python image - ignore values in resize

2009-03-06 Thread Travis Kirstine
I have be attempting to resize (downsample) a RGB image using the
python image library resize function.  Everything works fine but I
would like to exclude black values 0,0,0 from the calculations.  I
have tried creating a alpha mask based on black values then performing
the resize but that only create partially transparent tiles in the
regions that had black values

im = Image.open('src.tif')
multi = im.split
mask = im.point(lambda i: i == 0 and 255)# get 0 values
mask = mask.convert('L')
mask = ImageChops.invert(mask)  # make the 0  values 255 for transparency
out_im = Image.merge('RGBA', (multi[0], multi[1], multi[2], mask))
out_im = out_im.resize((100, 100), Image.ANTIALIAS)
out_im = out_im.convert('RGB')
out_im.save('dst.tif')



Any help would be great


-- 
Travis K.

Toronto, Canada

"She knows there's no success like failure
And that failure's no success at all."
-Bob Dylan-

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


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Limin Fu
>
> i agree it's not clear how this is related to python (although i can see
> the influence), but it does look like a nice language.


thanks.


>
>
> one thing i was surprised to find missing was that the discussion of types
> doesn't include classes (the discussion of macros doesn't include


Actually the documentation about types does not mean to explain the types in
a systematic way. It just tries to explain how to practically use them
implicitly and explicitly, and to point out where one should pay attention.
Classes surely should be discussed, but it didn't come into my mind when I
prepared the documentation. It will be discussed when I update the document.



> types,
> but that is more understandable).  i am wondering if you have hidden
> problems related to co and contra variance of types (like in java
> generics).


I have paid attention to the variance of types in some situations, but I am
not very sure if it is without problems. Until now, I still feel there are
still many things to be improved in the typing system. It would not be
surprising if there are hidden problems regarding this.



>
> also, why is "@" needed as well as yield?  in python, the presence of
> yield makes "@" implicit (i think).
>

You are right. I will change this. Thank you for pointing out this.

I am glad that, every time I announced the language in the python mailing
list, I received good comments and suggestions more often than in other
mailing lists and groups, that's why python mailing list is one of the first
places coming into my mind when I plan for an announcement of Dao;)



>
> andrew
>
>
> Limin Fu wrote:
> > Hi,
> >
> > This is to announce the first official release of Dao.
>
>
>


-- 
Limin Fu

http://www.daovm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2009-03-06 Thread Peter Otten
mattia wrote:

> Il Fri, 06 Mar 2009 14:06:14 +0100, Peter Otten ha scritto:
> 
>> mattia wrote:
>> 
>>> Hi, I'm new to python, and as the title says, can I improve this
>>> snippet (readability, speed, tricks):
>>> 
>>> def get_fitness_and_population(fitness, population):
>>> return [(fitness(x), x) for x in population]
>>> 
>>> def selection(fitness, population):
>>> '''
>>> Select the parent chromosomes from a population according to their
>>> fitness (the better fitness, the bigger chance to be selected) '''
>>> selected_population = []
>>> fap = get_fitness_and_population(fitness, population) pop_len =
>>> len(population)
>>> # elitism (it prevents a loss of the best found solution) # take
>>> the only 2 best solutions
>>> elite_population = sorted(fap)
>>> selected_population += [elite_population[pop_len-1][1]] +
>>> [elite_population[pop_len-2][1]]
>>> # go on with the rest of the elements for i in range(pop_len-2):
>>> # do something
>> 
>> def selection1(fitness, population, N=2):
>> rest = sorted(population, key=fitness, reverse=True) best = rest[:N]
>> del rest[:N]
>> # work with best and rest
>> 
>> 
>> def selection2(fitness, population, N=2):
>> decorated = [(-fitness(p), p) for p in population]
>> heapq.heapify(decorated)
>> 
>> best = [heapq.heappop(decorated)[1] for _ in range(N)] rest = [p for
>> f, p in decorated]
>> # work with best and rest
>> 
>> Both implementations assume that you are no longer interested in the
>> individuals' fitness once you have partitioned the population in two
>> groups.
>> 
>> In theory the second is more efficient for "small" N and "large"
>> populations.
>> 
>> Peter
> 
> Ok, but the fact is that I save the best individuals of the current
> population, than I'll have to choose the others elements of the new
> population (than will be N-2) in a random way. The common way is using a
> roulette wheel selection (based on the fitness of the individuals, if the
> total fitness is 200, and one individual has a fitness of 10, that this
> individual will have a 0.05 probability to be selected to form the new
> population). So in the selection of the best solution I have to use the
> fitness in order to get the best individual, the last individual use the
> fitness to have a chance to be selected. Obviously the old population anf
> the new population must have the same number of individuals.

You're right, it was a bad idea.

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
Gary Herron wrote:

>> Huh? How am I supposed to compare immutable types for identity then? Your
>> bizarre instruction would prohibit:
>>
>> if something is None
>>   
> 
> Just use:
> 
>   if something == None
> 
> It does *exactly* the same thing.

Wrong.

"something is None" is a pointer comparison. It's blindingly fast, and it
will only return True if something is the same object as None. Any other
object *must* return False.

"something == None" calls something.__eq__(None), which is a method of
arbitrary complexity, which may cause arbitrary side-effects. It can have
false positives, where objects with unexpected __eq__ methods may return
True, which is almost certainly not the intention of the function author
and therefore a bug.

[...]
> If they use a couple "something==None" instead of "something is None"
> in their code while learning Python, it won't hurt, 

Apart from the subtle bugs they introduce into their code.

> and they can change 
> their style when they understand the difference.  And meanwhile they
> will skip  traps newbies fall into when they don't understand these
> things yet.

How about teaching them the right reasons for using "is" instead of giving
them false information by telling them they should never use it?


-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
Gary Herron wrote:

> Robert Kern wrote:
...
>> Use "is" when you really need to compare by object identity and not
>> value.
> 
> But that definition is the *source* of the trouble.  It is *completely*
> meaningless to newbies.   Until one has experience in programming in
> general and experience in Python in particular, the difference between
> "object identity" and "value" is a mystery.

Then teach them the difference, rather than give them bogus advice.


> So in order to lead newbies away from this *very* common trap they often
> fall into, it is still a valid rule to say
> 
> Newbies: Never use "is" to compare immutable types.

Look in the standard library, and you will see dozens of cases of
first-quality code breaking your "valid" rule.

Your rule is not valid. A better rule might be:

Never use "is" to compare equality.

Or even:

Never use "is" unless you know the difference between identity and equality.

Or even:

Only use "is" on Tuesdays.

At least that last rule is occasionally right (in the same way a stopped
clock is right twice a day), while your rule is *always* wrong. It is never
correct to avoid using "is" when you need to compare for identity.

> of even better
> 
> Newbies: Never use "is" to compare anything.

Worse and worse! Now you're actively teaching newbies to write buggy code!


-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Gary Herron

Steven D'Aprano wrote:

Gary Herron wrote:

  

Emanuele D'Arrigo wrote:


Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand.
  
  

*Do NOT use "is" to compare immutable types.***Ever! **



Huh? How am I supposed to compare immutable types for identity then? Your
bizarre instruction would prohibit:

if something is None
  


Just use:

 if something == None

It does *exactly* the same thing. 



But...  I'm not (repeat NOT) saying *you* should do it this way.

I am saying that since newbies continually trip over incorrect uses of 
"is", they should be warned against using "is" in any situation until 
they understand the subtle nature or "is". 

If they use a couple "something==None" instead of "something is None"  
in their code while learning Python, it won't hurt, and they can change 
their style when they understand the difference.  And meanwhile they 
will skip  traps newbies fall into when they don't understand these 
things yet.


Gary Herron



which is the recommended way to compare to None, which is immutable. The
standard library has *many* identity tests to None.

I would say, *always* use "is" to compare any type whenever you intend to
compare by *identity* instead of equality. That's what it's for. If you use
it to test for equality, you're doing it wrong. But in the very rare cases
where you care about identity (and you almost never do), "is" is the
correct tool to use.


  

It is an implementation choice (usually driven by efficiency
considerations) to choose when two strings with the same value are stored
in memory once or twice.  In order for Python to recognize when a newly
created string has the same value as an already existing string, and so
use the already existing value, it would need to search *every* existing
string whenever a new string is created.



Not at all. It's quite easy, and efficient. Here's a pure Python string
constructor that caches strings.

class CachedString(str):
_cache = {}
def __new__(cls, value):
s =  cls._cache.setdefault(value, value)
return s

Python even includes a built-in function to do this: intern(), although I

believe it has been removed from Python 3.0.


  
Clearly that's not going to be efficient. 



Only if you do it the inefficient way.

  
However, the C implementation of Python does a limited version 
of such a thing -- at least with strings of length 1.



No, that's not right. The identity test fails for some strings of length
one.

  

a = '\n'
b = '\n'
len(a) == len(b) == 1


True
  

a is b


False


Clearly, Python doesn't intern all strings of length one. What Python
actually interns are strings that look like, or could be, identifiers:

  

a = 'heresareallylongstringthatisjustmade' \


... 'upofalphanumericcharacterssuitableforidentifiers123_'
  
 
b = 'heresareallylongstringthatisjustmade' \


... 'upofalphanumericcharacterssuitableforidentifiers123_'
  

a is b


True

It also does a similar thing for small integers, currently something
like -10 through to 256 I believe, although this is an implementation
detail subject to change.


  


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


Re: A Simple Tkinter Control Program--Slight Problem

2009-03-06 Thread W. eWatson

I like to see closure on a thread. This should do it.

from Tkinter import *
# Use of control variables and callbacks

def mycallback():
print "User entered:" , e.get()
print "Operation by 2 gives: ", e.get()*2, "and", v.get()*2

master = Tk()

#v=StringVar()
v=IntVar()
print v,type(v)
print v, type(v), type(v.get())
e = Entry(master,textvariable=v)
e.pack()
b = Button(master, text="Push to Print", width=10, command=mycallback)
b.pack()
e.focus_set()

v.set(123)

mainloop()


--
   W. eWatson

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

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


Re: This should be a simple question...

2009-03-06 Thread andrew cooke
Steven D'Aprano wrote:
> Steve Holden wrote:
>
>> If x and b are meant to be global than bite the bullet and *make* them
>> global.
>
> Well, there's global, and there's global.
>
> There's global to a few functions in a module, there's global to
> everything
> in a module, and global to an entire application. They're not necessarily
> the same thing.

this is probably drifting a bit far from the original question, but i have
used function scope to hide information "global" to a few functions.  the
idea is to use a factory function that generates them all.

  def factory():

a = 12
b = 34

def ifamultb(x):
  if a == x:
return x * b
  else:
return x

def somethinelse(x):
  blah blah

  (ifamultb, somethinelse) = factory()

that's off the top of my head.  you might need to work around python's
stupid scoping rules with hidden params:

def ifamultb(x, a=a):

etc

andrew


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


Re: This should be a simple question...

2009-03-06 Thread Steven D'Aprano
Steve Holden wrote:

> If x and b are meant to be global than bite the bullet and *make* them
> global.

Well, there's global, and there's global.

There's global to a few functions in a module, there's global to everything
in a module, and global to an entire application. They're not necessarily
the same thing.


-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Gary Herron

Robert Kern wrote:

On 2009-03-06 14:23, Gary Herron wrote:

Robert Kern wrote:

On 2009-03-06 13:46, Gary Herron wrote:

Emanuele D'Arrigo wrote:

Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand.


*Do NOT use "is" to compare immutable types.* **Ever! **


Well, "foo is None" is actually recommended practice



But since newbies are always falling into this trap, it is still a good
rule to say:

Newbies: Never use "is" to compare immutable types.

and then later point out, for those who have absorbed the first rule:

Experts: Singleton immutable types *may* be compared with "is",
although normal equality with == works just as well.


That's not really true. If my object overrides __eq__ in a funny way, 
"is None" is much safer.


Use "is" when you really need to compare by object identity and not 
value.


But that definition is the *source* of the trouble.  It is *completely* 
meaningless to newbies.   Until one has experience in programming in 
general and experience in Python in particular, the difference between 
"object identity" and "value" is a mystery.   

So in order to lead newbies away from this *very* common trap they often 
fall into, it is still a valid rule to say


   Newbies: Never use "is" to compare immutable types.

of even better

   Newbies: Never use "is" to compare anything.

This will help them avoid traps, and won't hurt their use of the 
language.  If they get to a point that they need to contemplate using 
"is", then almost be definition, they are not a newbie anymore, and the 
rule is still valid.


Gary Herron



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


Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
Emanuele D'Arrigo wrote:

> Hi everybody,
> 
> while testing a module today I stumbled on something that I can work
> around but I don't quite understand.

Why do you have to work around it?

What are you trying to do that requires that two strings should occupy the
same memory location rather than merely being equal?


> Why c and d point to two different objects with an identical string
> content rather than the same object?

Why shouldn't they?

-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Steven D'Aprano
Gary Herron wrote:

> Emanuele D'Arrigo wrote:
>> Hi everybody,
>>
>> while testing a module today I stumbled on something that I can work
>> around but I don't quite understand.
>>   
> 
> *Do NOT use "is" to compare immutable types.***Ever! **

Huh? How am I supposed to compare immutable types for identity then? Your
bizarre instruction would prohibit:

if something is None

which is the recommended way to compare to None, which is immutable. The
standard library has *many* identity tests to None.

I would say, *always* use "is" to compare any type whenever you intend to
compare by *identity* instead of equality. That's what it's for. If you use
it to test for equality, you're doing it wrong. But in the very rare cases
where you care about identity (and you almost never do), "is" is the
correct tool to use.


> It is an implementation choice (usually driven by efficiency
> considerations) to choose when two strings with the same value are stored
> in memory once or twice.  In order for Python to recognize when a newly
> created string has the same value as an already existing string, and so
> use the already existing value, it would need to search *every* existing
> string whenever a new string is created.

Not at all. It's quite easy, and efficient. Here's a pure Python string
constructor that caches strings.

class CachedString(str):
_cache = {}
def __new__(cls, value):
s =  cls._cache.setdefault(value, value)
return s

Python even includes a built-in function to do this: intern(), although I
believe it has been removed from Python 3.0.


> Clearly that's not going to be efficient. 

Only if you do it the inefficient way.

> However, the C implementation of Python does a limited version 
> of such a thing -- at least with strings of length 1.

No, that's not right. The identity test fails for some strings of length
one.

>>> a = '\n'
>>> b = '\n'
>>> len(a) == len(b) == 1
True
>>> a is b
False


Clearly, Python doesn't intern all strings of length one. What Python
actually interns are strings that look like, or could be, identifiers:

>>> a = 'heresareallylongstringthatisjustmade' \
... 'upofalphanumericcharacterssuitableforidentifiers123_'
>>>  
>>> b = 'heresareallylongstringthatisjustmade' \
... 'upofalphanumericcharacterssuitableforidentifiers123_'
>>> a is b
True

It also does a similar thing for small integers, currently something
like -10 through to 256 I believe, although this is an implementation
detail subject to change.


-- 
Steven

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Robert Kern

On 2009-03-06 14:23, Gary Herron wrote:

Robert Kern wrote:

On 2009-03-06 13:46, Gary Herron wrote:

Emanuele D'Arrigo wrote:

Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand.


*Do NOT use "is" to compare immutable types.* **Ever! **


Well, "foo is None" is actually recommended practice



But since newbies are always falling into this trap, it is still a good
rule to say:

Newbies: Never use "is" to compare immutable types.

and then later point out, for those who have absorbed the first rule:

Experts: Singleton immutable types *may* be compared with "is",
although normal equality with == works just as well.


That's not really true. If my object overrides __eq__ in a funny way, "is None" 
is much safer.


Use "is" when you really need to compare by object identity and not value.

--
Robert Kern

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

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Gary Herron

Robert Kern wrote:

On 2009-03-06 13:46, Gary Herron wrote:

Emanuele D'Arrigo wrote:

Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand.


*Do NOT use "is" to compare immutable types.* **Ever! **


Well, "foo is None" is actually recommended practice



But since newbies are always falling into this trap, it is still a good 
rule to say:


 Newbies:  Never use "is" to compare immutable types.

and then later point out, for those who have absorbed the first rule:

 Experts: Singleton immutable types *may* be compared with "is",
 although normal equality with == works just as well.

Gary Herron


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


Re: Asking for prophecy

2009-03-06 Thread Mensanator
On Mar 6, 1:23 pm, "andrew cooke"  wrote:
> 3 and 2.6 are compatible.  so develop on 3, to make sure you don't use old
> junk, and then switch to 2.6 if you need to.  there are a few wrinkles in
> doing so, but it is not a big problem.
>
> 3.0 is a nicer language.  it's cleaner and more consistent.  i think
> important libraries will move there.  

Probably, but until gmpy is available for 3.0,
3.0 does not exist yet as far as I'm concerned.

> no-one wants to do a perl.  it's the
> likely future and you can always jump back to 2.6 if needed.
>
> and in the long term, we will all die.
>
> andrew
>
>
>
> Stefan Spoettl wrote:
> > In the pass it was always a good idea to use the newest Python verison for
> > starting the development of a new application. First one could benefit
> > from the additional features and second one could be sure that the
> > community would have been passing during development.
>
> > Nowadays we have at least three Python versions (2.5, 2.6, 3.0) on our
> > machines and - damned! - I really don't know which version I should use
> > for my next development. The Unix-like systems as much as the major part
> > of well maintained third party libraries are remaining "penetrantly" on
> > 2.5. Why the vangard of the community don't like to use at least 2.6 for
> > bridging to the future Python? Is this the mutiny against the empery of
> > the BDFL or is the vangard just asking for some more time? If I want to
> > attest my personal attachment to the king by using 3.0, what will happen?
> > Will I be deserted someday?
>
> > Stefan--
> >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text -
>
> - Show quoted text -

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


Re: "/a" is not "/a" ?

2009-03-06 Thread John Nagle

Gary Herron wrote:

Emanuele D'Arrigo wrote:

Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand.   


*Do NOT use "is" to compare immutable types.***Ever! **


   Then it should be a detected error to do so.

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


Re: "/a" is not "/a" ?

2009-03-06 Thread Robert Kern

On 2009-03-06 13:46, Gary Herron wrote:

Emanuele D'Arrigo wrote:

Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand.


*Do NOT use "is" to compare immutable types.* **Ever! **


Well, "foo is None" is actually recommended practice

--
Robert Kern

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

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


Re: Indentations and future evolution of languages

2009-03-06 Thread Tim Rowe
2009/3/6  :
> This is an interesting post, it shows me that fitness plateau where
> design of Python syntax lives is really small, you can't design
> something just similar:
>
> http://unlimitednovelty.com/2009/03/indentation-sensitivity-post-mortem.html

I don't think the article is right that "it's silly to have some
expression/statement groupings indentation based and some grouped by
enclosing tokens" -- provided it's done right. The OCAML-based
language F# accepts OCAML enclosing tokens, but if you mark the groups
with indentation they're not necessary (but still legal). That seems
to me to work pretty cleanly.

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


How to replace the two last digits from an xml file?

2009-03-06 Thread awel
Hi,

I am trying to get a value from an xml file, increment it by 1,
replace by the new value and write another xml with the new value
inside.

I have found this code to get the line and it works but I have to do
everything manualy:

import re
lines = open("c:\\File1.xml").readlines()
for i in range(len(lines)):
if re.search('national.number', lines[i]):
lines[i] = lines[i].replace
('01aaa02','01aaa03')
open("File2.xml","w").writelines(lines)

The goal I am trying to reach is to create 30 different xml.

Could someone help me?

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


Re: where is the PyString_AsString in Python 3.0?

2009-03-06 Thread Benjamin Peterson
BigHand  gmail.com> writes:
> > There is no PyString_AsString. Everything
>> string is unicode now. (PyUnicode API)
> hello,Ben,
> could you give me an example? I almost know the
> PyUnicode API,but the
> docs of 3.0 is too brief for me.

PyString_FromString -> PyUnicode_FromString
PyString_Concat -> PyUnicode_Concat
etc...

To get a char * you have to explicitly encode the string with
PyUnicode_AsEncodedString.




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


Re: "/a" is not "/a" ?

2009-03-06 Thread Gary Herron

Emanuele D'Arrigo wrote:

Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand. 
  


*Do NOT use "is" to compare immutable types.***Ever! **

It is an implementation choice (usually driven by efficiency considerations) to 
choose when two strings with the same value are stored in memory once or twice. 
 In order for Python to recognize when a newly created string has the same 
value as an already existing string, and so use the already existing value, it 
would need to search *every* existing string whenever a new string is created.  
Clearly that's not going to be efficient.  However, the C implementation of 
Python does a limited version of such a thing -- at least with strings of 
length 1.

Gary Herron

  

a = "a"
b = "a"
a == b


True
  

a is b


True

  

c = "/a"
d = "/a"
c == d


True   # all good so far
  

c is d


False # ek!

Why c and d point to two different objects with an identical string
content rather than the same object?

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


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


Re: "/a" is not "/a" ?

2009-03-06 Thread Joshua Kugler
Emanuele D'Arrigo wrote:

 c = "/a"
 d = "/a"
 c == d
> True   # all good so far
 c is d
> False # ek!
> 
> Why c and d point to two different objects with an identical string
> content rather than the same object?

Because you instantiated two difference objects.
http://docs.python.org/reference/datamodel.html#objects-values-and-types
should get you started on Python and objects.

j

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


searching for an easy library to create OpenOffice spreadsheets

2009-03-06 Thread Krishnakant
Hello all,
I am looking out for a python library which does the followingg.
1, create and manipulate openoffice spreadsheets.
2, allow for cell formatting including merging cells.
3, allow for colouring cells and formatting data as bold italics etc.
4, alignment of data should be possible.
I looked at ooolib but did not find a method for merging cells.

any ideas?

happy hacking.
Krishnakant.
 

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


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Tim Greer
Limin Fu wrote:

> To Tim Greer and others:
> 
> Some people may think this kind of announcement are off topic in a
> group for another language. This is not exactly true. This is still
> about programming, there are so many programmers out there, who knows
> if there would be somebody interested in a new language. This
> announcement does not mean to threaten any language, I don't even
> think it is somewhere close to that. So take it easy.

I don't see it as a threat at all (I'm not sure how you read that from
what I said), and I honestly don't care that much, but it seems pretty
odd to post about a completely different language in groups that have
no relation.  Imagine people posting announcements about languages,
modules, extensions, etc in other language groups as they happened,
we'd see 1/2 the group's posts containing that sort of information.

You posted in the Python, Perl and Ruby groups, and it just seemed (was)
inappropriate and not a good way to get people interested (it can be a
turn off to see what could be considered spam).  Just because it's
another language doesn't make it on topic.  There are over a hundred of
them out there, and even more derivatives and it's just not usually
appreciated (though I don't pretend to speak for anyone else, but it's
a pretty accurate observation).

I don't assume ill intent by you, but it was questionable about why.
Anyway, it's not a knock on the language, I just don't think the Perl,
Ruby or Python groups are relevant (but maybe some people will find it
interesting and be glad you did -- of course, that could be said of any
post about anything).
-- 
Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc.
Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers
and Custom Hosting.  24/7 support, 30 day guarantee, secure servers.
Industry's most experienced staff! -- Web Hosting With Muscle!
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Dao, the official 1.0 version is released

2009-03-06 Thread Limin Fu
Honest to say, there is no solid connection between Dao and Python.
It's just that I had received some good suggestions and comments from
these groups when I made a few previous announcements in these groups.
So I guessed somebody might be interested in Dao, and thought it might
be a good idea to announce it here again.

Nevertheless, Python is one of the few languages from which Dao tried
to learn something. I have paid a lot of my attention to Python during
the development of Dao. Once a time I even created a module trying to
allow calling Python functions and using python objects in Dao
scripts, it was a long time ago, probably even before this language is
named as Dao. Unfortunately I hadn't time to continue to develop that
module.


To Tim Greer and others:

Some people may think this kind of announcement are off topic in a
group for another language. This is not exactly true. This is still
about programming, there are so many programmers out there, who knows
if there would be somebody interested in a new language. This
announcement does not mean to threaten any language, I don't even
think it is somewhere close to that. So take it easy.



On 3月6日, 下午7时13分, s...@pobox.com wrote:
> Limin> This is to announce the first official release of Dao.
>
> What's the connection to Python?
>
> --
> Skip Montanaro - s...@pobox.com -http://www.smontanaro.net/

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


Re: Unusual Python interpreter problem with os.fork()

2009-03-06 Thread DLitgo
On Mar 6, 7:20 am, Jean-Paul Calderone  wrote:
> On Fri, 6 Mar 2009 05:00:03 -0800 (PST), DLitgo  wrote:
> >Hello everyone,
>
> >I have a curious problem which I'm wondering if anyone here can shed
> >some light on. I'm basically just following along with a guide which
> >is going through some of the os module, and I'm running some examples
> >in the python interpreter on mac os x (accessed through terminal/
> >bash).
>
> >Basically all I did was use os.fork() which caused this strange
> >problem:
>
> >Macintosh:~ $ python
> >Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
> >[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> >Type "help", "copyright", "credits" or "license" for more information.
>
>  import os
>  pid = os.fork()
>
> As soon as this returns, you have two CPython processes reading from stdin
> and writing to stdout.  They fight over your input and their output gets
> interleaved in non-deterministic ways.  Basically, you probably don't ever
> want to do this.
>
> Jean-Paul

Okay cool, I guess the example wasn't meant to be run in the
interpreter then :) Thanks for the reply.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading from text

2009-03-06 Thread Paul McGuire
On Feb 17, 11:03 am, oamram  wrote:
> Hi All,
> new to python. i have a directory with about 50 text file and i need to
> iterate through them and get
> line 7 to 11 from each file and write those lines into another file(one file
> that will contain all lines).
>

import glob
file("output.txt","w").write('\n'.join( "".join(f.readlines()
[7:11+1]) ) for f in glob.glob("targetdir/*.txt"))

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


Re: Asking for prophecy

2009-03-06 Thread andrew cooke

3 and 2.6 are compatible.  so develop on 3, to make sure you don't use old
junk, and then switch to 2.6 if you need to.  there are a few wrinkles in
doing so, but it is not a big problem.

3.0 is a nicer language.  it's cleaner and more consistent.  i think
important libraries will move there.  no-one wants to do a perl.  it's the
likely future and you can always jump back to 2.6 if needed.

and in the long term, we will all die.

andrew


Stefan Spoettl wrote:
> In the pass it was always a good idea to use the newest Python verison for
> starting the development of a new application. First one could benefit
> from the additional features and second one could be sure that the
> community would have been passing during development.
>
> Nowadays we have at least three Python versions (2.5, 2.6, 3.0) on our
> machines and - damned! - I really don't know which version I should use
> for my next development. The Unix-like systems as much as the major part
> of well maintained third party libraries are remaining "penetrantly" on
> 2.5. Why the vangard of the community don't like to use at least 2.6 for
> bridging to the future Python? Is this the mutiny against the empery of
> the BDFL or is the vangard just asking for some more time? If I want to
> attest my personal attachment to the king by using 3.0, what will happen?
> Will I be deserted someday?
>
> Stefan--
> http://mail.python.org/mailman/listinfo/python-list
>


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


"/a" is not "/a" ?

2009-03-06 Thread Emanuele D'Arrigo
Hi everybody,

while testing a module today I stumbled on something that I can work
around but I don't quite understand.

>>> a = "a"
>>> b = "a"
>>> a == b
True
>>> a is b
True

>>> c = "/a"
>>> d = "/a"
>>> c == d
True   # all good so far
>>> c is d
False # ek!

Why c and d point to two different objects with an identical string
content rather than the same object?

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


Re: how to prevent python import from looking into the current directory

2009-03-06 Thread Ben Finney
(Could you please set a valid email address for people to contact you
if necessary?)

TP  writes:

> I would like to prevent the loading of modules in the current
> directory.

You will, I think, like the new distinction between “absolute” and
“relative” imports http://www.python.org/dev/peps/pep-0328/>.

-- 
 \ “All my life I've had one dream: to achieve my many goals.” |
  `\—Homer, _The Simpsons_ |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Asking for prophecy

2009-03-06 Thread Stefan Spoettl
In the pass it was always a good idea to use the newest Python verison for 
starting the development of a new application. First one could benefit from the 
additional features and second one could be sure that the community would have 
been passing during development.

Nowadays we have at least three Python versions (2.5, 2.6, 3.0) on our machines 
and - damned! - I really don't know which version I should use for my next 
development. The Unix-like systems as much as the major part of well maintained 
third party libraries are remaining "penetrantly" on 2.5. Why the vangard of 
the community don't like to use at least 2.6 for bridging to the future Python? 
Is this the mutiny against the empery of the BDFL or is the vangard just asking 
for some more time? If I want to attest my personal attachment to the king by 
using 3.0, what will happen? Will I be deserted someday?

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


Re: New User - Using tutorial and Docs - POST returns 302 Found

2009-03-06 Thread JohnV

> Sorry, I think you didn't get my later post -- than in fact was from a  
> month ago...
> Seehttp://article.gmane.org/gmane.comp.python.general/613312/
> urllib2 should handle a 302 redirect automatically.
>
> --
> Gabriel Genellina

I went to the link you provided and sure enough there was your post.
However, the date was all wrong.  I did not even submit to this list
until March 2,2009 so the date on your other post was probably in
European format 03/02/2009 but read as US 02/03/2009.  In any case,
thank you.  The code does get my request to the page however the data
sent in the POST does not arrive with the request.


import httplib, urllib, urllib2

f = open(r'C:\Users\Owner\Desktop\mydata.txt', 'r')
read_data = f.read()
f.close()

params = urllib.urlencode({'textarea1': read_data})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
url = "http://www.thenational.us:80/pages/start/test/getpost.html";
req = urllib2.Request(url, params, headers)
response = urllib2.urlopen(req)
data = response.read()
response.close()
print data

f = open(r'C:\Users\Owner\Desktop\pydata.txt', 'a')
f.write(data)
f.close()



I even changed the params line to to:
params = urllib.urlencode({'textarea1': 'somedata'})

then I tried taking part of the header out ("Accept": "text/plain")
like this:
headers = {"Content-type": "application/x-www-form-urlencoded"}

I still get to the getpost.html page because response has the html
from that page, but textarea1 does not get passed.

Putting :80 or leaving it out of the URL does not seem to matter
either way I get to the getpost page, just no data is passed.

I am running Python 2.5 r25:51908 MSC v.1318 32 bit (Intel) on wind32
and after doing a search on Python Post problems, I read that urllib2
handled 302 redirect POST incorrectly at least in 2.5x . See
http://bugs.python.org/issue1401

Maybe my code is still lacking some command, or I need to install a
newer version of Python.  That option (installing) seems a little
daunting to me as I have no experience but I can learn if that will
fix the problem for me.

Thanks for the help so far, any furhter suggestions appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Winsound Problems on Vista 64

2009-03-06 Thread Terry Reedy

Casey wrote:

I have a new laptop that came with Vista 64 and I'm having problems
with some of my older code that I use for multimedia processing.  I
narrowed the problem down to the winsound library; any attempt to play
sounds results in a fatal error.  The simplest case is:


from winsound import Beep
Beep(440, 2)

Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: Failed to beep

I have been able to recreate this problem in Python 2.6.1 (32-bit),
3.0.1 (32-bit) and 3.0.1 (AMD64 bit, which I hope is compliant with my
IA64 CPU). 


IA64 is Itanium, not Pentium, and AMD64 is not compatible with that.
But I doubt that is what your laptop has.

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


  1   2   3   >