Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Russ P.
On Jan 24, 9:54 pm, Luis Zarrabeitia  wrote:
> Quoting "Russ P." :
>
> > Once again, if you have the source code for the library (and the right
> > to modify it), how does the "power" lie with the library implementer
> > rather than you the user?
>
> > You say you don't want to "fork" the library. Let's stipulate for the
> > sake of argument that a one-line change is indeed a "fork."
>
> It is. For starters, I'd lose the information of "this attribute was intended 
> to
> be internal and I'm accessing it anyway".

Not really. When you get a new version of the library and try to use
it, you will quickly get a reminder about the change (assuming your
tests provide sufficient converage, and also assuming that the
attribute is not made public in the new version). So you don't really
even need to keep track of the change.

> > Think
> > about what you are saying. You are saying that you should dictate how
> > the producer of the library should implement it because you don't want
> > to be bothered to "fork" it.
>
> No. I am not dictating _anything_. The beauty of it, you don't have to do
> _anything_ for this to happen.

You are trying to dictate that the library implementer not be allowed
to use enforced access restriction. And, in the larger sense, you are
trying to dictate that access restrictions not be enforced in Python.

> Now, you may say that I'm trying to force you to relax and do nothing instead 
> of
> complaining because the language I use doesn't put enough restrictions on me.

And you are trying to put restrictions on anyone who might prefer to
enforce access restrictions. If you don't allow them to do that, you
are restricting them.

> > If you don't like his design decisions,
> > shouldn't the onus be on *you* to make the trivial change necessary to
> > get access to what you want?
>
> Or contacting him about it and maybe send him a patch, sure, why not. But this
> has nothing to do with enforced data hiding. Having obj._public_var is just as
> badly designed as having "private public_var".

Sure, go ahead and contact him. If he agrees that a private attribute
should be public, then the problem is solved. But if he does not
agree, he should not be forced to bend to your desire.

> > Imagine a person who repairs computers. He is really annoyed that he
> > constantly has to remove the cover to get at the guts of the computer.
> > So he insists that computers cases should be made without covers.
> > After all, manufacturers put covers on computers only because they
> > don't trust us and think we're too "stupid" to safely handle an
> > uncovered computer box.
>
> > That is logically equivalent to your position on enforced access
> > restrictions in software.
>
> Do you realize that most computer cases are trivially easy to open? (Nevermind

That was exactly my point. Deleting the word "private" (or whatever)
is also trivially easy if you have access to the source code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Luis Zarrabeitia

Quoting "Russ P." :

> Once again, if you have the source code for the library (and the right
> to modify it), how does the "power" lie with the library implementer
> rather than you the user?
> 
> You say you don't want to "fork" the library. Let's stipulate for the
> sake of argument that a one-line change is indeed a "fork." 

It is. For starters, I'd lose the information of "this attribute was intended to
be internal and I'm accessing it anyway".

> Think
> about what you are saying. You are saying that you should dictate how
> the producer of the library should implement it because you don't want
> to be bothered to "fork" it.

No. I am not dictating _anything_. The beauty of it, you don't have to do
_anything_ for this to happen.

Now, you may say that I'm trying to force you to relax and do nothing instead of
complaining because the language I use doesn't put enough restrictions on me.

> If you don't like his design decisions,
> shouldn't the onus be on *you* to make the trivial change necessary to
> get access to what you want?

Or contacting him about it and maybe send him a patch, sure, why not. But this
has nothing to do with enforced data hiding. Having obj._public_var is just as
badly designed as having "private public_var".

> Imagine a person who repairs computers. He is really annoyed that he
> constantly has to remove the cover to get at the guts of the computer.
> So he insists that computers cases should be made without covers.
> After all, manufacturers put covers on computers only because they
> don't trust us and think we're too "stupid" to safely handle an
> uncovered computer box.
> 
> That is logically equivalent to your position on enforced access
> restrictions in software.

Do you realize that most computer cases are trivially easy to open? (Nevermind
that there are other reasons... dust, protection against physical damage, etc.
My PC is locked enough to protect them, but opened enough so I can "play" with
it whenever I need)

> > And, FYI, when programming in java, C++ or C#, I do use "private" and
> > "protected" variables, not becasue I want to forbid others from using it,
> but
> > because it is [rightly?] assumed that everything marked as public is safe
> to use
> > - and I consider that a strong enough "external" reason to do it.
> 
> You could just use leading underscores and note their meaning in the
> documentation. If that's such a great approach, why not do it? Yes, I
> know, it's not a widely used convention in those other languages. Fair
> enough. 

It is not a widely used convention, and that is reason enough for me. It's quite
a contradiction to say in the code "this thing is safe to use" and then document
it as "highly unsafe - do not touch". With Java and C# I'm more lenient (and
work more with explicit interfaces rather than just the public/protected/private
thing).

BTW, the actual 'private' case for most languages is a different beast: it is
used to prevent namespace pollution/name clashes. I can't easily simulate those
with public attributes in C#/Java/C++ (but I concede that their 'privates' do a
better job at this than python's self.__local)

> But you could still do it if it's such a good idea.

I think someone commented in this thread about a case where he had to do exactly
that.

[copying from your other reply]

> But what if I want an automatic check to verify that I am using it as
> the author intended? Is that unreasonable? Think of enforced access
> restriction as an automatic "assert" every time an attribute is
> accessed that it is not a private attribute.

I think that was a reply to a message where I said that I used pylint run those
checks on third party libraries. And I obviously can do the same with my own
code. I don't have threading now, so I can't check if I really said that. If I
didn't, well, I'm saying it now.

Now, as Paul Robin pointed out, those statics checks done by pylint can't catch
a runtime workaround using eval, exec or getattr/setattr. But neither can C++.

By the way, I urge you to try to write code that pylint doesn't complain about.
It's easy to not be satisfied with the checks it provides if you haven't used 
it.




-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: OCaml, Language syntax, and Proof Systems

2009-01-24 Thread Xah Lee
Addendum:

The above is not a terrible insight, but i suppose it should be useful
for some application. Today, there's huge number of languages, each
screaming ME! To name a few that are talked about by geekers, there's
Arc, Clojure, Scalar, F#, Erlang, Ruby, Groovy, Python 3, Perl6. (for
a big list, see: Proliferation of Computing Languages) So, if i want
to learn another lang down the road, and wish it to be a joy to use,
usable docs, large number of usable libraries, or well supported,
practical community that doesn't loop into monad or tail recursion
every minute, then which one should i buy? With criterions of
industrial background, not culty, lang beauty matter not that much, in
mind, i think Erlang, F# would be great choices, while langs like Qi,
Oz, Arc, Perl6, would be most questionable.

Perm url:

• Language, Purity, Cult, and Deception
  http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html

http://xahlee.blogspot.com/2009/01/language-purity-cult-and-deception.html

  Xah
∑ http://xahlee.org/

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


Re: Two import questions in Python 3.0

2009-01-24 Thread Kay Schluehr
On 24 Jan., 18:51, Scott David Daniels  wrote:
> Kay Schluehr wrote:
> > On 24 Jan., 09:21, "Gabriel Genellina"  wrote:
> >> If you run A.py as a script, it does not "know" it lives inside a package.
> >> You must *import* A for it to become aware of the package.
> >> Also, the directory containing the script comes earlier than PYTHONPATH
> >> entries in sys.path -- so watch for that case too.
> > Thanks, yes. I always make the same error thinking that a directory
> > with the ritual __init__ file is actually a package ( as some kind of
> > platonic entity ), something that is more obvious to me than it is to
> > the runtime. The relative import semantics introduced with Python 2.5
> > has made the error just visible that was hidden to me for about a
> > decade. Shit.
>
> Temper the language a bit.  You lose your effectiveness by some people
> reading the color of your words, rather than their meaning in code.

Sigh, yes... sorry. I'm just too frustrated. Actually I don't even
know why the import machinery is such a mess and I don't want to spend
a huge amount of time ( like Brett Cannon ) to figure it out.

I'll spent a few hours of time writing a script that turns all
relative paths into absolute ones without changing the source
otherwise. Then I'm at least done with that and won't ever see the
"relative import in non-packages" exceptions anymore in any code I
touch ( I can also ignore __package__, -m and all the other
workarounds ). It's not the first time Python is in my way but this
time it hurts.
--
http://mail.python.org/mailman/listinfo/python-list


Re: OCaml, Language syntax, and Proof Systems

2009-01-24 Thread Xah Lee
Language, Purity, Cult, and Deception

Xah Lee, 2009-01-24

[this essay is roughly a 10 years personal retrospect of some
languages, in particular Scheme and Haskell.]

I learned far more Ocaml in the past 2 days than the fucking 2 months
i tried to learn Haskell, with 10 years of “I WANT TO BELIEVE” in
haskell.

The Haskell's problem is similar to Scheme lisp, being academic and of
little industrial involvement. About 10 years ago, during the dot com
era around 1999, where scripting war is going on (Perl, tcl,
Applescript, Userland Frontier, with in the corner Python, Ruby, Icon,
Scheme, in the air of Java, HTML 3, CSS, CGI, javascript), i was sold
a lie by Scheme lisp. Scheme, has a aura of elegance and minimalism
that's one hundred miles in radius. I have always been a advocate of
functional programing, with a heart for formal methods. Scheme, being
a academic lang, has such a association. At the time, Open Source and
Linux have just arrived on the scene and screaming the rounds in the
industry, along with Apache & Perl. The Larry Wall scumbag and Eric
Raymond motherfucker and Linus T moron and Richard Stallman often
appears in interviews in mainstream media. Richard Stallman's FSF with
its GNU, is quick to make sure he's not forgotten, by a campaign on
naming of Linux to GNU/Linux. FSF announced that Scheme is its chosen
scripting lang for GNU system. Plans and visions of Guile — the new
Scheme implementation, is that due to Scheme Lisp's power will have
lang conversion abilities on the fly so programers can code in other
lang if they wanted to, anywhere in the GNU platform. Around that
time, i also wholeheartedly subscribed to some A Brave Gnu World
bulletin of FSF with high expectations.

Now, it's 2009. Ten years have passed. Guile disappeared into
oblivion. Scheme is tail recursing in some unknown desert. PHP
practically and quietly surpassed the motherfucking foghorn'd Perl in
early 2000s to become the top 5 languages. Python has surfaced to
became a mainstream. Ruby is the hip kid on the block. Where is
Scheme? O, you can still hear these idiots debating tail recursions
among themselves in newsgroups. Tail recursion! Tail recursion! And
their standard the R6RS in 2007, by their own consensus, is one fucked
up shit.

In 2000, i was a fair expert in unix technologies. Sys admin to
several data center's solaris boxes each costing some 20 grands.
Master of Mathematica and Perl but don't know much about any other
lang or lang in general. Today, i am a expert of about 5 languages and
working knowledge with tens or so various ones. There is nothing in
Scheme i'd consider elegant, not remotely, even if we only consider
R4RS.

Scheme, like other langs with a cult, sold me lie that lasted 10
years. Similarly, Haskell fucked me with a tag of “no assignment”
purity. You can try to learn the lang for years and all you'll learn
is that there's something called currying and monad. I regret i
learned python too in 2006. Perl is known for its intentional
egregious lies, lead by the demagogue Larry Wall (disclaimer: opinion
only). It fell apart unable to sustain its “post-modernistic”
deceptions. Python always seemed reasonable to me, until you stepped
into it. You learned that the community is also culty, and is into
certain grand visions on beauty & elegance with its increasingly
complex syntax soup with backward incompatible python 3.0. The python
fuckheads sport the air of “computer science R us”, in reality they
are idiots about the same level of Perl mongers. (Schemers and Haskell
people at least know what they are talking about. They just don't have
the know how of the industry.)

I think my story can teach tech geekers something. In my experience,
the langs that are truely a joy to learn and use, are those sans a
cult. Mathematica, javascript, PHP, are all extremely a joy to use.
Anything you want to do or learn how to do, in so far that the lang is
suitable, can be done quickly. Their docs are to the point. And today
i have to include Ocaml. It's not about whether the lang is
functional, or whether the lang is elegant, or what theoretical power
it has. Also, lang of strong academic background such as Scheme and
Haskell are likely to stay forever there, regardless what is the
technical nature of the lang. The background of the community, makes
half what the language is.

Disclaimer: All mentions of real persons are opinion only.

  Xah
∑ http://xahlee.org/

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


Re: Is (-1 ==True) True or False? Neither

2009-01-24 Thread Oktay Şafak

Terry Reedy wrote:

Oktay Şafak wrote:

That's what I'm trying to say: it would be more meaningful if 
int.__eq__ did a boolean comparison when the other operand is a boolean.


For that to be done, int would have to know about its subclass, which 
generally is bad design.


Good point, but of course it can be done without making the int type 
know about the specifics of its subclass.




The reason is that when someone writes (-1 == True) he is clearly, 
definitely, absolutely asking for a boolean comparison, not a 
numerical one.


I would say that the person does not understand Python and that the code 
is probably buggy.


 > As I said before, this is  weird code;

It is a bad idea to accommodate the language and interpreter to weird 
code which should never be written.


Again, good point. Agreed.



Well, I agree that explicit is better than implicit: when one wants to 
use the numerical values of True or False, he should make it explicit 
and use int(True) or int(False).


The reason to make bool a subclass of int is to avoid having to do that. 
 You do not have to like this fact of Python but it has been decided and 
will not change.


 > We never write counter += True, for example.

But you might write counter += name, where you know name is bound to a 
bool.  As I said, issubclass(bool, int) just so one would not have to 
write counter += int(name).


OK, my fault. Arithmetical operations was not my point, I was just 
trying to talk about integer values of True and False in an equality 
comparison context with other numbers. Of course the fact that 
issubclass(bool, int) is very handy in calculations like that.





If you want to cast an object to a boolean, use bool() on it.


Well, I can tell you in response that if you are interested in a 
boolean's *integer* value, than make it explicit and use int(True). 


A Python bool *is* an int already: isinstance(True, int) returns True!


I know, you don't need to shout. What I was trying to say is that using 
the integer value of a boolean *in a comparison with a number* doesn't 
make much sense *to me*. I am not trying to change Python or whatever, I 
am extremely pleased with it as it is. But that doesn't mean I like each 
and every decision that has gone into it. Like everybody else, there are 
things that doesn't quite fit in for me and I am trying to understand 
better. I just came across this behavior while trying something in the 
interpreter and wanted to discuss with people more knowledgeable than 
myself. Please keep calm!



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


syntax color lang source code in blogs or website

2009-01-24 Thread Xah Lee
For those of you using emacs, here's the elisp code that allows you to
syntax color computer language source code in your blog or website.

http://xahlee.org/emacs/elisp_htmlize.html

to comment, here:
http://xahlee.blogspot.com/2009/01/dehtmlize-source-code-in-emacs-lisp.html

  Xah
∑ http://xahlee.org/

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


Re: Is (-1 ==True) True or False? Neither

2009-01-24 Thread Oktay Şafak

I don't see how fixing this makes harder to treat True and False as
first-class objects. If doing the right thing takes some special casing
then be it, but I don't think it's so.


True in ['something', False]

In your semantics, this would evaluate to True because ('something' == 
True) is True.




No, it wouldn't. We are talking about integer-boolean equality 
comparisons, not boolean-string ones. But I get your point.



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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Rhodri James

On Sun, 25 Jan 2009 00:31:14 -, Tim Rowe  wrote:


2009/1/24 Rhodri James :



My experience with medium-sized organisations (50-100 people) is that
either you talk to Fred directly, or it doesn't happen.  In particular
the more people (especially PHBs) that get involved, the slower the
change will come and the less like your original requirement it will
look.  Each person, no matter how technically adept, has a significant
chance of misunderstanding what it is you need and/or expressing it
poorly to the next person in line.


So you talk to Fred, and he changes the "pong" library function to go
"ping", as you wish. Unfortulately, neither of you know that Alice is
depending on Fred's "pong" library function to go "pong" as specified,
and is totally stuffed when he delivers it and it goes "ping". That's
why changes to specifications need to go through a proper
specification change procedure if the team (not the organisation) is
more than a few people.


And, not coincidentally, why specification will take at least twice as
long as you thought humanly possible, and any implementation you do
before it's complete will probably have to be thrown away.  The
productivity of a team large enough that they don't all talk to each
other anyway drops quite dramatically as one consequence of this.

This also assumes that the "proper specification change procedure"
works, which seems to be a bit on the optimistic side in many cases.

But we digress.

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


Re: *.python.org broken?

2009-01-24 Thread Tim Chase

Is anybody else having trouble accessing sites (including www, docs,
wiki) in the python.org tree, or is it just me? (Or just .au?)


I've had problems[1] browsing them (most irksomely, the docs) 
from Dillo thanks to what are apparently poor handling of IPv6 
fallback rules.  Dillo gets an IPv6 IP address back from DNS, 
tries it and fails because my ISP or router doesn't talk IPv6. 
However Dillo fails to fallback to IPv4 which does work (bug 
filed with the Debian maintainers of Dillo[2]).  If I switch to 
using a less broken browser (Epiphany, Lynx, FireFox/IceWeasel, 
Safari, telnet:80, urllib), it works fine here in the Dallas 
area.  If I disable IPv6 on my Linux box (not a great loss at 
this point), Dillo works as well.


Tests to check:

 Can you resolve the IP address from the name?
bash$ dig docs.python.org
bash$ dig -6 docs.python.org

 Can you ping the target IP address?
bash$ ping docs.python.org
bash$ ping 82.94.164.162
   (try ping6 as well)

 Can you traceroute to the IP address (and where does it die)?
bash$ traceroute docs.python.org
bash$ traceroute -6 docs.python.org

 Can you telnet:80 to the target IP address?
bash$ telnet docs.python.org 80
GET / HTTP/1.1
host: docs.python.org

 Have you tried from other local ISPs? (cafe, work, school)


-tkc

PS:  Thanks again, Martin, for your tips in troubleshooting this 
for me.


[1]
http://mail.python.org/pipermail/python-list/2008-November/517812.html

[2]
http://bugs.debian.org/507251




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


Re: Possible to slice a string with unpacked tuple?

2009-01-24 Thread python
Terry,

Hi, I'm the OP in question.

> the OP should simply write myString[slice(*myTuple)]

My tuples define positions in a fixed width string for parsing values.
So rather than 'unpacking' tuples, I'm using slice() to directly define
actual field positions, eg.

field_1 = slice( 4, 7 )
field_2 = slice( 7, 9 )
etc ...

This allows me to extract the field values as follows:

for line in myOpenFile:
value_1 = line[ field_1 ]
value_2 = line[ field_2 ]
etc.

IMO, this makes a common task like extracting fields very natural and
elegant.

I LOVE THIS LANGUAGE!! (to echo another recent thread in this forum)

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


Re: Possible to slice a string with unpacked tuple?

2009-01-24 Thread Terry Reedy

Benjamin Peterson wrote:

MRAB  mrabarnett.plus.com> writes:
Does myString[myTuple[0] : myTuple[1]] count as unpacking? If it does, 
then how about myString.__getslice__(*myTuple)?


Please don't use special method names directly and especially not
__getslice__(). It's deprecated and will be removed.


It is gone in 3.0.  In 3.0, at least, and perhaps later 2.x (not sure)
the OP should simply write
   myString[slice(*myTuple)]
which is the semantic equivalent of
   myString[myTuple[0]:myTuple[1]]

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Russ P.
On Jan 24, 5:09 pm, Luis Zarrabeitia  wrote:

> I didn't say "at all". Those were your words, not mine.
> I said that it makes no sense that the power lies on _you_ instead of on _my
> team_. And, when I said that, I recall we were talking about the python
> language, not C.

Once again, if you have the source code for the library (and the right
to modify it), how does the "power" lie with the library implementer
rather than you the user?

You say you don't want to "fork" the library. Let's stipulate for the
sake of argument that a one-line change is indeed a "fork." Think
about what you are saying. You are saying that you should dictate how
the producer of the library should implement it because you don't want
to be bothered to "fork" it. If you don't like his design decisions,
shouldn't the onus be on *you* to make the trivial change necessary to
get access to what you want?

Imagine a person who repairs computers. He is really annoyed that he
constantly has to remove the cover to get at the guts of the computer.
So he insists that computers cases should be made without covers.
After all, manufacturers put covers on computers only because they
don't trust us and think we're too "stupid" to safely handle an
uncovered computer box.

That is logically equivalent to your position on enforced access
restrictions in software.

> And, FYI, when programming in java, C++ or C#, I do use "private" and
> "protected" variables, not becasue I want to forbid others from using it, but
> because it is [rightly?] assumed that everything marked as public is safe to 
> use
> - and I consider that a strong enough "external" reason to do it.

You could just use leading underscores and note their meaning in the
documentation. If that's such a great approach, why not do it? Yes, I
know, it's not a widely used convention in those other languages. Fair
enough. But you could still do it if it's such a good idea.
--
http://mail.python.org/mailman/listinfo/python-list


Re: String comparision

2009-01-24 Thread Gabriel Genellina
En Sat, 24 Jan 2009 15:08:08 -0200, S.Selvam Siva   
escribió:



I am developing spell checker for my local language(tamil) using python.
I need to generate alternative word list for a miss-spelled word from the
dictionary of words.The alternatives must be as much as closer to the
miss-spelled word.As we know, ordinary string comparison wont work here .
Any suggestion for this problem is welcome.


I think it would better to add Tamil support to some existing library like  
GNU aspell: http://aspell.net/
You are looking for "fuzzy matching":  
http://en.wikipedia.org/wiki/Fuzzy_string_searching
In particular, the Levenshtein distance is widely used; I think there is a  
Python extension providing those calculations.


--
Gabriel Genellina

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


Re: *.python.org broken?

2009-01-24 Thread tgvaughan
On Jan 25, 12:19 pm, Philip Semanchuk  wrote:
> On Jan 24, 2009, at 8:06 PM, tgvaug...@gmail.com wrote:
>
> > Hi all,
>
> > Is anybody else having trouble accessing sites (including www, docs,
> > wiki) in the python.org tree, or is it just me? (Or just .au?)
>
> No problem here in Durham, NC, USA.

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


Re: Is (-1 ==True) True or False? Neither

2009-01-24 Thread Terry Reedy

Oktay Şafak wrote:

That's what I'm trying to say: it would be more meaningful if int.__eq__ 
did a boolean comparison when the other operand is a boolean.


For that to be done, int would have to know about its subclass, which 
generally is bad design.


The reason is that when 
someone writes (-1 == True) he is clearly, definitely, absolutely asking 
for a boolean comparison, not a numerical one.


I would say that the person does not understand Python and that the code 
is probably buggy.


> As I said before, this is  weird code;

It is a bad idea to accommodate the language and interpreter to weird 
code which should never be written.


Well, I agree that explicit is better than implicit: when one wants to 
use the numerical values of True or False, he should make it explicit 
and use int(True) or int(False).


The reason to make bool a subclass of int is to avoid having to do that. 
 You do not have to like this fact of Python but it has been decided 
and will not change.


> We never write counter += True, for example.

But you might write counter += name, where you know name is bound to a 
bool.  As I said, issubclass(bool, int) just so one would not have to 
write counter += int(name).



If you want to cast an object to a boolean, use bool() on it.


Well, I can tell you in response that if you are interested in a 
boolean's *integer* value, than make it explicit and use int(True). 


A Python bool *is* an int already: isinstance(True, int) returns True!
Adding the bool subclass around 2.3 or so was a convenience that makes 
code and output clearer, but not a necessity.  Python did fine without 
it just as many other languages do.


Terry Jan Reedy

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


Re: Is (-1 ==True) True or False? Neither

2009-01-24 Thread Robert Kern

On 2009-01-24 19:07, Oktay Şafak wrote:

Robert Kern wrote:

On 2009-01-24 17:00, oktaysa...@superonline.com wrote:

Hi all,

I ran into a strange case.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
...
>>> -1 == True
False
>>> -1 == False
False

This works though:
>>> if -1:
print "OK"

OK

After some head scratching, I realized that:
- bool is a subclass of int and that True and False evaluates to 1 and
0, so -1 is equal to neither; and
- The if -1: statement probably works by treating -1 as bool(-1).


Yes.


Good.




But I can't help finding the former comparison behavior odd. I admit
that it is odd to write such code but when someone writes -1 == True,
the intention is clearly a boolean comparison, not a numerical value
comparison, isn't it?


Not to me. The rules of Python state that the object on the left hand
side is asked first how to compare the two values. Only if that fails
is the object on the right hand side asked how to compare the objects.


OK.


As far as I understand, to do this comparison, python is casting
(loosely speaking) True to its numerical value, rather than casting -1
to its boolean value.


Not really. No casting goes on at all.


Of course, I said loosely speaking.


bool is just one of the types that int.__eq__ knows how to handle
because bool is a subclass of int. Vice-versa, bool.__eq__ knows how
to handle ints, and it also does a numerical comparison; it never
casts to a boolean.


That's what I'm trying to say: it would be more meaningful if int.__eq__
did a boolean comparison when the other operand is a boolean. And
bool.__eq__ should as well do a boolean comparison when the other
operand is an integer (or even a number). The reason is that when
someone writes (-1 == True) he is clearly, definitely, absolutely asking
for a boolean comparison, not a numerical one. As I said before, this is
weird code; but using the True built-in for checking whether a number's
value is equal to 1 would be even weirder.


So don't do it. There really aren't many use cases for comparing with a boolean. 
Just call bool() on the object.



So, my question is: wouldn't it make more sense to do just the opposite,
i.e. cast -1 to its boolean value and do a boolean comparison of the
operands, when one of the operands is True or False?

Or is this too fancy? What do you think?


I think that being explicit is better than being implicit.


Well, I agree that explicit is better than implicit: when one wants to
use the numerical values of True or False, he should make it explicit
and use int(True) or int(False), but one is never interested in a
boolean's numerical value (which is nonsense, IMHO). We never write
counter += True, for example.


Actually, I sum up booleans quite often.


If you want to cast an object to a boolean, use bool() on it.


Well, I can tell you in response that if you are interested in a
boolean's *integer* value, than make it explicit and use int(True).


The two positions are not symmetrical. Your position requires special-casing 
equality testing; Python's position doesn't.



When
I write

assert i == True

I'm not trying to make sure that i is equal to one, I am trying to make
sure that it evaluates to True (of course True is redundant here but it
can make the code more readable). If I was interested in the former
case, it would be most natural to write assert i == 1 but I'm interested
in the latter and I think Python's treatment is not quite right here.


Then just do "assert i" or "assert bool(i)" and be done with it. There's no need 
to do any comparisons at all.



 > Making special rules when comparing with booleans makes it harder to
 > treat True and False as first-class objects.

I don't see how fixing this makes harder to treat True and False as
first-class objects. If doing the right thing takes some special casing
then be it, but I don't think it's so.


True in ['something', False]

In your semantics, this would evaluate to True because ('something' == True) is 
True.


--
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: *.python.org broken?

2009-01-24 Thread Philip Semanchuk


On Jan 24, 2009, at 8:06 PM, tgvaug...@gmail.com wrote:


Hi all,

Is anybody else having trouble accessing sites (including www, docs,
wiki) in the python.org tree, or is it just me? (Or just .au?)


No problem here in Durham, NC, USA. 
--

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Russ P.
On Jan 24, 4:17 pm, Luis Zarrabeitia  wrote:
> Quoting "Russ P." :
>
> > On Jan 23, 6:36 pm, Luis Zarrabeitia  wrote:
>
> > > > Makes *no* sense? There's *no* good reason *at all* for the original
> > > > author to hide or protect internals?
>
> > > My bad, sorry.
> > > It makes sense... if the original author is an egotist who believes he
> > must
> > > control how I use that library.
>
> > If the original author provides you with the source code and the right
> > to modify it, he cannot possibly control how you use the library. You
> > can trivially disable any access controls. But for some reason that's
> > not enough for you.
>
> No, I'm not satisfied with forking python just to use sys._getframe.

Calling a one-word change a "fork" is quite a stretch, I'd say.

> > Has it occurred to you that some users might actually *want* access
> > controls? Maybe some users want to actually use the library as the
> > author intended it to be used. What a bizarre concept!
>
> Huh?
> Then... use it as the author intended. I am _not_ forcing you to use the
> obj._protected attributes!

But what if I want an automatic check to verify that I am using it as
the author intended? Is that unreasonable? Think of enforced access
restriction as an automatic "assert" every time an attribute is
accessed that it is not a private attribute.

I may want this automatic verification in my own code just for peace
of mind. More importantly, a project manager may want it to verify
that no one on the development team is accessing private attributes.
Sure, he could do that with code reviews, but code reviews are far
more expensive (and less reliable in some ways) than a simple check
enforced by the language itself.

Without enforced access protection, depending on code reviews to
detect the use of private attributes is a bit like depending on
security guards to keep doors closed without putting locks on the
doors. You don't need a lock on a door if you can afford to post a
security guard there full time, but doesn't it make more sense to put
a lock on the door and have a security guard check it only
occasionally?
--
http://mail.python.org/mailman/listinfo/python-list


Re: *.python.org broken?

2009-01-24 Thread r
On Jan 24, 7:06 pm, tgvaug...@gmail.com wrote:
> Hi all,
>
> Is anybody else having trouble accessing sites (including www, docs,
> wiki) in the python.org tree, or is it just me? (Or just .au?)
>
> Cheers,
>
> Tim

No problem here???
--
http://mail.python.org/mailman/listinfo/python-list


*.python.org broken?

2009-01-24 Thread tgvaughan
Hi all,

Is anybody else having trouble accessing sites (including www, docs,
wiki) in the python.org tree, or is it just me? (Or just .au?)

Cheers,

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Luis Zarrabeitia

Quoting Steven D'Aprano :

> On Fri, 23 Jan 2009 21:36:59 -0500, Luis Zarrabeitia wrote:
> 
> > Quoting Steven D'Aprano :
> >> Makes *no* sense? There's *no* good reason *at all* for the original
> >> author to hide or protect internals?
> > 
> > My bad, sorry.
> > It makes sense... if the original author is an egotist who believes he
> > must control how I use that library.
> 
> Then I guess Guido must be such an egotist, because there's plenty of 
> internals in Python that you can't (easy) mess with.

Yeap, ignore the second part, and claim that I only said this.
 
> > Or, if external forces make him do
> > it (maybe like, 'oh, if I change python, then I'm not using python
> > anymore').
> 
> That parenthesised comment makes no sense to me.

It was directly countering your 'list' example. _I_ don't want to change
_python_, nor python's assumptions and assurances. A standard python that can
segfault would be no python. Again, if you think that means that deep down I
like enforced data hiding, so be it.

> [...]
> > If a variable is marked as... I don't like 'private', I'll call it
> > 'implementation detail', I would not use it without good reason. Not
> > even by subclassing it. Why do you assume that I'd change list._length
> > if I could? I wouldn't.
> 
> I didn't say you would change it on a whim. I said that *if* it were 
> exposed to Python code, you *could* change it. You might change it 
> because you thought you had a good reason to. You might change it by 
> accident. You might not realise the consequences of changing it. Who 
> knows? It doesn't matter what your motives are.

Exactly, they don't matter to you, unless you happen to be running my code.

> My point is that you claimed that there is no good reason at all for 
> hiding implementation details. Python is full of implementation details 
> which are quite effectively hidden from Python programmers. So there are 
> two possibilities:

I didn't say "at all". Those were your words, not mine.
I said that it makes no sense that the power lies on _you_ instead of on _my
team_. And, when I said that, I recall we were talking about the python
language, not C.

> (1) you are right that it "makes no sense" (your words) for the original 
> author (in this case, Guido) to hide those implementation details from 
> Python programmers; or

Just to be clear: I think the opposite.
He made a language and interpreter, and it ensures that it will not segfault
because of incorrect pure python code. That is my blackbox. In doing that, he
made a language where I don't have to worry that much about enforcing access
restrictions. Again, if you think that means that I want enforced data hiding in
python, so be it. 

> (2) you are wrong that it "makes no sense", because there is at least one 
> case where the original author (Guido again) did a sensible thing by 
> hiding implementation details.

hiding the implementation details of a C implementation... not python.

> In an effort to avoid going round and round in circles, let me explicitly 
> say that option (2) does not imply that it always makes sense to hide 
> implementation details.

Huh?
It makes sense to hide implementations details. I'd say it always makes sense.
What doesn't make sense is that someone fights so vehemently to stop me from
getting at them, on my code, on my systems. 

> [...]
> >> So what you're saying is that the fundamental design of Python -- to be
> >> a high-level  language that manages memory for you while avoiding
> >> common programming errors such as buffer overflows -- makes "no sense".
> >> Is that what you intended?
> > 
> > Yes, that's what I intended, obviously. I'd like to have buffer
> > overflows in python. In case you don't understand irony: don't go
> > putting words in my mouth. I'm not putting words in yours.
> 
> And neither am I. I'm pointing out the logical implications of your 
> position. If you find those implications unpleasant, then perhaps you 
> should modify your position to be less extreme and more realistic.

But it is realistic. You put the words "at all", and you shifted the discussion
from Python to C, and from programs in python to python's implementation.

[snip the comments about the advantages of data hiding. We are not talking about
data hiding, we are talking about having data hiding enforced against me]

> > I stand by my words - but not by your "interpretation" of them:
> > 
> >> > What makes no sense is that it should be in the original author's
> >> > power to decide, if he is not part of _our_ team.
> > 
> > Do you _really_ read from that sentence that I should dislike python
> > because it makes it a bit harder to get a buffer overflow with their
> > native types?
> 
> Well, you tell me: does it make sense for Guido to have decided to make 
> it hard for pure Python developers to cause buffer overflows?

Yes it does.
And this answers my question... You do consider the fact that I like python, 
that I like that python is not C, and that I

Re: Is (-1 ==True) True or False? Neither

2009-01-24 Thread Terry Reedy

oktaysa...@superonline.com wrote:

Hi all,

I ran into a strange case.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
(Intel)] on win32

...
 >>> -1 == True
False
 >>> -1 == False
False

This works though:
 >>> if -1:
print "OK"

OK

After some head scratching, I realized that:
- bool is a subclass of int and that True and False evaluates to 1 and 
0,


Yes, for historical and practical reasons.


so -1 is equal to neither; and


NO builtin objects other than numbers equal to 1 or 0 are equal to True 
or False.



- The if -1: statement probably works by treating -1 as bool(-1).


'if condition:' *always* works by calling bool() on the condition, which 
is why one should *never* write 'if bool(exp):'.



But I can't help finding the former comparison behavior odd.


Every object other than numbers equal to 0 or 1 has the same behavior.


I admit that it is odd to write such code but when someone writes -1 == True,


It is odd to write such code because the result of comparing two 
constants is or could be known when it is written.  So while one could 
write an optimizer to replace such comparisons with the known value at 
compile time, no one has done so.  (There is an optimizer that sometimes 
replaces arithmetic operations on number constants, but that is because 
writing code that way may make it clearer: for instance, 1<<13 versus 8192.)


the intention is clearly a boolean comparison, not a numerical value 
comparison, isn't it?


Nope.  Expecially if either side of the expression in the code is a name 
or collection slot.  As far as the compiler is concerned, '-1' is an 
expression that evaluates to an object and 'True' is another expression 
that evaulates to another object and '==' is a comparison operator which 
it compiles to a call to code that calls the appropriate rich comparison 
methods of either or both of the two objects.


As far as I understand, to do this comparison, python is casting 
(loosely speaking) True to its numerical value, rather than casting -1 
to its boolean value.


I think that this is speaking so loosely as to be misleading.  'Cast' 
has a couple of meaning, neither of which means 'treat a subclass 
instance as a base class instance.'  Subclass instances are 
automatically base class instances and are treated as such by default 
unless there is a subclass method that over-rides the base class method. 
 Bool does *not* over-ride int comparison methods.


>>> bool.__eq__ is int.__eq__
True

I suspect that the only methods to bool are __new__ (which returns one 
of the only two instances allowed), __str__, and __repr__ (which return 
'False' or 'True' instead of '0' or '1').  Bools are ints, not 'cast to' 
ints.


So, my question is: wouldn't it make more sense to do just the opposite, 
i.e. cast -1 to its boolean value and do a boolean comparison of the 
operands, when one of the operands is True or False?


That would require that ints be subclassed from bool, which does not work.

Terry Jan Reedy

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


Re: Is (-1 ==True) True or False? Neither

2009-01-24 Thread Oktay Şafak

Robert Kern wrote:

On 2009-01-24 17:00, oktaysa...@superonline.com wrote:

Hi all,

I ran into a strange case.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
...
 >>> -1 == True
False
 >>> -1 == False
False

This works though:
 >>> if -1:
print "OK"

OK

After some head scratching, I realized that:
- bool is a subclass of int and that True and False evaluates to 1 and
0, so -1 is equal to neither; and
- The if -1: statement probably works by treating -1 as bool(-1).


Yes.


Good.




But I can't help finding the former comparison behavior odd. I admit
that it is odd to write such code but when someone writes -1 == True,
the intention is clearly a boolean comparison, not a numerical value
comparison, isn't it?


Not to me. The rules of Python state that the object on the left hand 
side is asked first how to compare the two values. Only if that fails is 
the object on the right hand side asked how to compare the objects.


OK.


As far as I understand, to do this comparison, python is casting
(loosely speaking) True to its numerical value, rather than casting -1
to its boolean value.


Not really. No casting goes on at all. 


Of course, I said loosely speaking.

bool is just one of the types that int.__eq__ knows how to handle 
because bool is a subclass of int. 
Vice-versa, bool.__eq__ knows how to handle ints, and it also does a 
numerical comparison; it never casts to a boolean.


That's what I'm trying to say: it would be more meaningful if int.__eq__ 
did a boolean comparison when the other operand is a boolean. And 
bool.__eq__ should as well do a boolean comparison when the other 
operand is an integer (or even a number). The reason is that when 
someone writes (-1 == True) he is clearly, definitely, absolutely asking 
for a boolean comparison, not a numerical one. As I said before, this is 
weird code; but using the True built-in for checking whether a number's 
value is equal to 1 would be even weirder.





So, my question is: wouldn't it make more sense to do just the opposite,
i.e. cast -1 to its boolean value and do a boolean comparison of the
operands, when one of the operands is True or False?

Or is this too fancy? What do you think?


I think that being explicit is better than being implicit. 


Well, I agree that explicit is better than implicit: when one wants to 
use the numerical values of True or False, he should make it explicit 
and use int(True) or int(False), but one is never interested in a 
boolean's numerical value (which is nonsense, IMHO). We never write 
counter += True, for example.


If you want to cast an object to a boolean, use bool() on it. 


Well, I can tell you in response that if you are interested in a 
boolean's *integer* value, than make it explicit and use int(True). When 
I write


assert i == True

I'm not trying to make sure that i is equal to one, I am trying to make 
sure that it evaluates to True (of course True is redundant here but it 
can make the code more readable). If I was interested in the former 
case, it would be most natural to write assert i == 1 but I'm interested 
in the latter and I think Python's treatment is not quite right here.


> Making special rules when comparing with booleans makes it harder to
> treat True and False as first-class objects.

I don't see how fixing this makes harder to treat True and False as 
first-class objects. If doing the right thing takes some special casing 
then be it, but I don't think it's so.


Anyway, thanks for the response.

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


Re: RegEx issues

2009-01-24 Thread Gabriel Genellina
En Sat, 24 Jan 2009 19:03:26 -0200, Sean Brown gmail.com>  
<" escribió:



Using python 2.4.4 on OpenSolaris 2008.11

I have the following string created by opening a url that has the
following string in it:

td[ct] = [[ ... ]];\r\n

The ...  above is what I'm interested in extracting which is really a
whole bunch of text. So I think the regex \[\[(.*)\]\]; should do it.
The problem is it appears that python is escaping the \ in the regex
because I see this:

reg = '\[\[(.*)\]\];'
reg

'\\[\\[(.*)\\]\\];'

Now to me looks like it would match the string - \[\[ ... \]\];


No. Python escape character is the backslash \; if you want to include a  
backslash inside a string, you have to double it. By example, these are  
all single character strings: 'a'  '\n'  '\\'
Coincidentally (or not), the backslash has a similar meaning in a regular  
expression: if you want a string containing \a (two characters) you should  
write "\\a".
That's rather tedious and error prone. To help with this, Python allows  
for "raw-string literals", where no escape interpretation is done. Just  
put an r before the opening quote: r"\(\d+\)" (seven characters; matches  
numbers inside parenthesis).


Also, note that when you *evaluate* an expression in the interpreter (like  
the lone "reg" above), it prints the "repr" of the result: for a string,  
it is the escaped contents surrounded by quotes. (That's very handy when  
debugging, but may be confusing if don't know how to interpret it)


Third, Python is very permissive with wrong escape sequences: they just  
end up in the string, instead of flagging them as an error. In your case,  
\[ is an invalid escape sequence, which is left untouched in the string.


py> reg = r'\[\[(.*)\]\];'
py> reg
'\\[\\[(.*)\\]\\];'
py> print reg
\[\[(.*)\]\];
py> len(reg)
13


Which obviously doesn't match anything because there are no literal \ in
the above string. Leaving the \ out of the \[\[ above has re.compile
throw an error because [ is a special regex character. Which is why it
needs to be escaped in the first place.


It works in this example:

py> txt = """
... Some text
... and td[ct] = [[ more things ]];
... more text"""
py> import re
py> m = re.search(reg, txt)
py> m
<_sre.SRE_Match object at 0x00AC66A0>
py> m.groups()
(' more things ',)

So maybe your r.e. doesn't match the text (the final ";"? whitespace?)
For more info, see the Regular Expressions HOWTO at  
http://docs.python.org/howto/regex.html


--
Gabriel Genellina

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Tim Rowe
2009/1/24 Rhodri James :


> My experience with medium-sized organisations (50-100 people) is that
> either you talk to Fred directly, or it doesn't happen.  In particular
> the more people (especially PHBs) that get involved, the slower the
> change will come and the less like your original requirement it will
> look.  Each person, no matter how technically adept, has a significant
> chance of misunderstanding what it is you need and/or expressing it
> poorly to the next person in line.

So you talk to Fred, and he changes the "pong" library function to go
"ping", as you wish. Unfortulately, neither of you know that Alice is
depending on Fred's "pong" library function to go "pong" as specified,
and is totally stuffed when he delivers it and it goes "ping". That's
why changes to specifications need to go through a proper
specification change procedure if the team (not the organisation) is
more than a few people.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-24 Thread Luis Zarrabeitia

Quoting "Russ P." :

> On Jan 23, 6:36 pm, Luis Zarrabeitia  wrote:
> 
> > > Makes *no* sense? There's *no* good reason *at all* for the original
> > > author to hide or protect internals?
> >
> > My bad, sorry.
> > It makes sense... if the original author is an egotist who believes he
> must
> > control how I use that library.
> 
> If the original author provides you with the source code and the right
> to modify it, he cannot possibly control how you use the library. You
> can trivially disable any access controls. But for some reason that's
> not enough for you.

No, I'm not satisfied with forking python just to use sys._getframe.

> Has it occurred to you that some users might actually *want* access
> controls? Maybe some users want to actually use the library as the
> author intended it to be used. What a bizarre concept!

Huh?
Then... use it as the author intended. I am _not_ forcing you to use the
obj._protected attributes!

Even I run pylint against third party libraries just to assess if the risk of
them messing with someone else's internals is worth taking (as in the case of
inspect.currentframe, which is exactly the same as sys._getframe) or not (random
library downloaded from the net).

> Oh, but only a paranoid fool could possibly want access controls, eh?
> Who's the egotist here?

See? You too changed what I said. Somehow you managed to delete the _other_
situation I gave. Not worth correcting it. 

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: I'm a python addict !

2009-01-24 Thread Russ P.
On Jan 24, 4:03 pm, Robert Kern  wrote:
> On 2009-01-23 22:25, Aahz wrote:
>
> > In article,
> > Linuxguy123  wrote:
> >> I just started using python last week and I'm addicted.
>
> > Welcome!  Just be aware that excessive Perl-bashing is considered
> > somewhat tasteless on this newsgroup, but the occasional snide comment
> > should be fine.  ;-)
>
> Or bash-bashing for that matter.  :-)
>
> but-zsh-really-is-better'ly yrs,
>
> --
> 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

Come to think of it, when I use bash to run a series of python
scripts, I could call it "bashing Python."
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a string into a datetime object

2009-01-24 Thread Mark.Petrovic
On Jan 24, 10:56 am, Hrvoje Niksic  wrote:
> "Mark.Petrovic"  writes:
> > Might someone comment on why %f is not accepted as a valid field
> > directive in:
>
>  from datetime import datetime
>  created="2009-01-24 16:04:55.882788"
>  dt = datetime.strptime(created,"%Y-%m-%d %H:%M:%S.%f")
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/
> > python2.5/_strptime.py", line 321, in strptime
> >     (bad_directive, format))
> > ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f'
>
> > This is for Python 2.5.1 under OS X.
>
> time.strptime is documented to use the same set of directives as
> time.strftime, 
> andhttp://docs.python.org/library/time.html#time.strftimedoesn't mention
> a %f directive.

Thank you for the timely reply.

I guess I got mixed up by looking at the Python 2.6.1 docs, but used
the Python 2.5.1 interpreter:

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

wherein datetime.html does show the availability of the %f directive
(if I'm reading all this correctly).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regex for Python 2.7

2009-01-24 Thread John Machin
On Jan 25, 7:23 am, MRAB  wrote:
> Some time ago I discovered this difference between regular expressions
> in Python and Perl:
>
> Python
>
>         \A matches at start of string
>         \Z matches at end of string
>
> Perl
>
>         \A matches at start of string
>         \Z matches before terminal newline or at end of string
>         \z matches at end of string
>
> In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^
> and \Z != $ in single-string mode.
>
> Obviously, changing Python's \Z to match Perl's could break existing
> code. \z could be added, but with the opposite meaning to Perl's:
>
>         Python's \Z == Perl's \z
>         Python's \z == Perl's \Z
>
> Would that be confusing?
>
> Any suggests welcome.

IIRC there was an exchange some years ago where the perl guy (Larry?)
admitted that he goofed and the consensus was that what Python had
done was better.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Possible to slice a string with unpacked tuple?

2009-01-24 Thread Benjamin Peterson
MRAB  mrabarnett.plus.com> writes:
> Does myString[myTuple[0] : myTuple[1]] count as unpacking? If it does, 
> then how about myString.__getslice__(*myTuple)?

Please don't use special method names directly and especially not
__getslice__(). It's deprecated and will be removed.




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


Re: why is this invalid b = a += b ?

2009-01-24 Thread Terry Reedy

Stef Mientki wrote:

hello,

I can assign a value to more than 1 variable (name) in one line:

a = b = 3

So evaluation of this line must start at the right part.

But the following is not allowed:

b = 2
a = b += 1


This strikes me as slightly incoherent.  Given that v op=exp is mostly 
that same as v = v op exp, I suppose you expect a = b += 1 to be mostly 
the same as a = b = b+1, but what would you do with a += b = 1, or even 
a *= b += 1.  There is some virtur to restricting augmented assignment 
to one target and one delimiter.  Even that seems to cause some trouble.


tjr

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


Re: RegEx issues

2009-01-24 Thread John Machin
On Jan 25, 5:59 am, Scott David Daniels  wrote:
> Sean Brown wrote:
> > I have the following string ...:  "td[ct] = [[ ... ]];\r\n"
> > The ... (representing text in the string) is what I'm extracting 
> > So I think the regex \[\[(.*)\]\]; should do it.
> > The problem is it appears that python is escaping the \ in the regex
> > because I see this:
>  reg = '\[\[(.*)\]\];'
>  reg
> > '\\[\\[(.*)\\]\\];'
> > Now to me looks like it would match the string - \[\[ ... \]\];
> > ...
>
> OK, you already have a good answer as to what is happening.
> I'll mention that raw strings were put in the language exactly for
> regex work.  They are useful for any time you need to use the backslash
> character (\) within a string (but not as the final character).
> For example:
>      len(r'\a\b\c\d\e\f\g\h') == 16 and len('\a\b\c\d\e\f\g\h') == 13
>
> If you get in the habit of typing regex strings as r'...' or r"...",
> and examining the patters with print(somestring), you'll ease your life.

All excellent suggestions, but I'm surprised that nobody has mentioned
the re.VERBOSE format.

Manual sez:
'''
re.X
re.VERBOSE
This flag allows you to write regular expressions that look nicer.
Whitespace within the pattern is ignored, except when in a character
class or preceded by an unescaped backslash, and, when a line contains
a '#' neither in a character class or preceded by an unescaped
backslash, all characters from the leftmost such '#' through the end
of the line are ignored.

That means that the two following regular expression objects that
match a decimal number are functionally equal:

a = re.compile(r"""\d +  # the integral part
   \.# the decimal point
   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
'''

My comments:
(1)"looks nicer" is not the point; it's understandability
(2) if you need a space, use a character class ->[ ]<- not an
unescaped backslash ->\ <-
(3) the indentation in the manual doesn't fit my idea of "looks
nicer"; I'd do
a = re.compile(r"""
\d +  # the integral part
\.# the decimal point
\d *  # some fractional digits
""", re.X)
(4) you can aid understandability by more indentation especially when
you have multiple capturing expressions and (?..) gizmoids e.g.
r"""
(
 . # prefix
)
(
 (?..) # look-back assertion
 (?) # etc etc
)
"""
Worth a try if you find yourself going nuts getting the parentheses
matching.

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


Re: Can webbrowser module get source code?

2009-01-24 Thread Benjamin Peterson
Muddy Coder  yahoo.com> writes:
> I want to go
> further: to get the source code of the webpage being displayed. Is it
> possible to do it? I tried webbrow.get() but didn't work. Somebody can
> help? Thanks!

To do this, you actually need to fetch the page yourself:

import urllib2
page_source = urllib2.urlopen("http://someaddress.com";).read()

> 




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


Re: I'm a python addict !

2009-01-24 Thread Robert Kern

On 2009-01-23 22:25, Aahz wrote:

In article,
Linuxguy123  wrote:

I just started using python last week and I'm addicted.


Welcome!  Just be aware that excessive Perl-bashing is considered
somewhat tasteless on this newsgroup, but the occasional snide comment
should be fine.  ;-)


Or bash-bashing for that matter.  :-)

but-zsh-really-is-better'ly yrs,

--
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: Is (-1 ==True) True or False? Neither

2009-01-24 Thread Robert Kern

On 2009-01-24 17:00, oktaysa...@superonline.com wrote:

Hi all,

I ran into a strange case.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
...
 >>> -1 == True
False
 >>> -1 == False
False

This works though:
 >>> if -1:
print "OK"

OK

After some head scratching, I realized that:
- bool is a subclass of int and that True and False evaluates to 1 and
0, so -1 is equal to neither; and
- The if -1: statement probably works by treating -1 as bool(-1).


Yes.


But I can't help finding the former comparison behavior odd. I admit
that it is odd to write such code but when someone writes -1 == True,
the intention is clearly a boolean comparison, not a numerical value
comparison, isn't it?


Not to me. The rules of Python state that the object on the left hand side is 
asked first how to compare the two values. Only if that fails is the object on 
the right hand side asked how to compare the objects.



As far as I understand, to do this comparison, python is casting
(loosely speaking) True to its numerical value, rather than casting -1
to its boolean value.


Not really. No casting goes on at all. bool is just one of the types that 
int.__eq__ knows how to handle because bool is a subclass of int. Vice-versa, 
bool.__eq__ knows how to handle ints, and it also does a numerical comparison; 
it never casts to a boolean.



So, my question is: wouldn't it make more sense to do just the opposite,
i.e. cast -1 to its boolean value and do a boolean comparison of the
operands, when one of the operands is True or False?

Or is this too fancy? What do you think?


I think that being explicit is better than being implicit. If you want to cast 
an object to a boolean, use bool() on it. Making special rules when comparing 
with booleans makes it harder to treat True and False as first-class objects.


--
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: I'm a python addict !

2009-01-24 Thread MRAB

Terry Reedy wrote:

Benjamin Kaplan wrote:



On Sat, Jan 24, 2009 at 5:35 PM, Lie Ryan > wrote:


On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote:

 > I just started using python last week and I'm addicted.

you need to try this:

import antigravity

http://xkcd.com/353/


Just be careful with that. That guy was still floating 129 comics 
later (3 comics = 1 week). And still going "Woo Python". You can see 
him floating near the peak of Mt. Everest.


http://xkcd.com/482/


For a Python 'program', see http://xkcd.com/534/


It doesn't follow PEP 8!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regex for Python 2.7

2009-01-24 Thread MRAB

Gabriel Genellina wrote:
> En Sat, 24 Jan 2009 18:23:51 -0200, MRAB 
> escribió:
>
>> Some time ago I discovered this difference between regular expressions
>> in Python and Perl:
>>
>> Python
>>
>> \A matches at start of string
>> \Z matches at end of string
>>
>> Perl
>>
>> \A matches at start of string
>> \Z matches before terminal newline or at end of string
>> \z matches at end of string
>>
>> In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^
>> and \Z != $ in single-string mode.
>
> Why do you want the two to be equivalent? Isn't a good thing that you
> have both alternatives (\Z and $)? Use whichever is adequate in each 
case.

>
Python's \Z is equivalent to Perl's \z, but there's no equivalent to 
Perl's \Z in multi-line mode.

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


Re: why is this invalid b = a += b ?

2009-01-24 Thread MRAB

Stef Mientki wrote:

hello,

I can assign a value to more than 1 variable (name) in one line:

a = b = 3

So evaluation of this line must start at the right part.

But the following is not allowed:

b = 2
a = b += 1

I would think that if b has a value, and the formula is evaluated
from right to left, there's nothing wrong with the above formula.


Assignment is a statement, not an expression. That's why:

if a = 0:
...

is illegal.

However, simple serial assignment such as:

a = b = 3

is useful enough to be supported as a special case.
--
http://mail.python.org/mailman/listinfo/python-list


Re: I'm a python addict !

2009-01-24 Thread Terry Reedy

Benjamin Kaplan wrote:



On Sat, Jan 24, 2009 at 5:35 PM, Lie Ryan > wrote:


On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote:

 > I just started using python last week and I'm addicted.

you need to try this:

import antigravity

http://xkcd.com/353/


Just be careful with that. That guy was still floating 129 comics later 
(3 comics = 1 week). And still going "Woo Python". You can see him 
floating near the peak of Mt. Everest.


http://xkcd.com/482/


For a Python 'program', see http://xkcd.com/534/

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


Re: Regex for Python 2.7

2009-01-24 Thread Gabriel Genellina
En Sat, 24 Jan 2009 18:23:51 -0200, MRAB   
escribió:



Some time ago I discovered this difference between regular expressions
in Python and Perl:

Python

\A matches at start of string
\Z matches at end of string

Perl

\A matches at start of string
\Z matches before terminal newline or at end of string
\z matches at end of string

In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^
and \Z != $ in single-string mode.


Why do you want the two to be equivalent? Isn't a good thing that you have  
both alternatives (\Z and $)? Use whichever is adequate in each case.


--
Gabriel Genellina

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


why is this invalid b = a += b ?

2009-01-24 Thread Stef Mientki

hello,

I can assign a value to more than 1 variable (name) in one line:

a = b = 3

So evaluation of this line must start at the right part.

But the following is not allowed:

b = 2
a = b += 1

I would think that if b has a value,
and the formula is evaluated from right to left,
there's nothing wrong with the above formula.

thanks
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Can webbrowser module get source code?

2009-01-24 Thread Muddy Coder
Hi All,

I played the demo of webbrowser module, with the code below:

import webbrowser
url = 'https://login.yahoo.com'
webbrowser.open_new_tab(url)

when I ran the code, it popped out a webpage nicely. I want to go
further: to get the source code of the webpage being displayed. Is it
possible to do it? I tried webbrow.get() but didn't work. Somebody can
help? Thanks!


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


Re: TEST=`which test` equivalent in python?

2009-01-24 Thread Gabriel Genellina
En Sat, 24 Jan 2009 17:03:33 -0200, Jay Jesus Amorin  
 escribió:



*SVNLOOK_PATH=os.system('which svnlook')*


You've been told what's wrong with that. But instead of fixing how to  
invoke "which", use distutils.spawn.find_executable instead:


py> from distutils.spawn import find_executable
py> find_executable('svnlook')
'c:\\apps\\svn\\bin\\svnlook.exe'

--
Gabriel Genellina

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


Is (-1 ==True) True or False? Neither

2009-01-24 Thread oktaysafak
Hi all,

I ran into a strange case. 

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
...
>>> -1 == True
False
>>> -1 == False
False

This works though:
>>> if -1:
     print "OK"

OK

After some head scratching, I realized that:
- bool is a subclass of int and that True and False evaluates to 1 and 0, so -1 is equal to neither; and 
- The if -1: statement probably works by treating -1 as bool(-1).

But I can't help finding the former comparison behavior odd. I admit that it is odd to write such code but when someone writes -1 == True, the intention is clearly a boolean comparison, not a numerical value comparison, isn't it? 

As far as I understand, to do this comparison, python is casting (loosely speaking) True to its numerical value, rather than casting -1 to its boolean value.

So, my question is: wouldn't it make more sense to do just the opposite, i.e. cast -1 to its boolean value and do a boolean comparison of the operands, when one of the operands is True or False?

Or is this too fancy? What do you think?




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


Re: Possible to slice a string with unpacked tuple?

2009-01-24 Thread python
MRAB,

> Does myString[myTuple[0] : myTuple[1]] count as unpacking? 

I'm not sure my use of the term 'unpacking' was totally correct, but,
yes, that's what I was hoping to avoid with a simpler solution.

> then how about myString.__getslice__(*myTuple)?

Very interesting.

I'm going to try Ben's slice() object suggestion.

Thanks for your help,
Malcolm

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


Re: Possible to slice a string with unpacked tuple?

2009-01-24 Thread python
Benjamin,
> Use the built-in slice.
Perfect!! That's exactly what I was looking for - I didn't know
this object existed.
> What's wrong with unpacking the tuple?
I'm extracting fields from a huge, multi-gig log file. I was
trying to avoid doing something like myString[ myTuple[ 0 ]:
myTuple[ 1 ] )  millions of times in a loop.

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


Re: Possible to slice a string with unpacked tuple?

2009-01-24 Thread MRAB

pyt...@bdurham.com wrote:

  Is there a way to slice a string with a tuple without unpacking the tuple?

 >>> myString = "111-222-333-444"
 >>> myString[ 4: 7 ]
'222'

Is there some way I could perform an identical slicing operation with a 
tuple like ( 4, 7 ) without having to unpack the tuple?


 >>> myTuple = ( 4, 7 )

Thanks!

Does myString[myTuple[0] : myTuple[1]] count as unpacking? If it does, 
then how about myString.__getslice__(*myTuple)?

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


Re: I'm a python addict !

2009-01-24 Thread Benjamin Kaplan
On Sat, Jan 24, 2009 at 5:35 PM, Lie Ryan  wrote:

> On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote:
>
> > I just started using python last week and I'm addicted.
>
> you need to try this:
>
> import antigravity
>
> http://xkcd.com/353/
>

Just be careful with that. That guy was still floating 129 comics later (3
comics = 1 week). And still going "Woo Python". You can see him floating
near the peak of Mt. Everest.

http://xkcd.com/482/


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


Re: Possible to slice a string with unpacked tuple?

2009-01-24 Thread Benjamin Kaplan
On Sat, Jan 24, 2009 at 5:31 PM,  wrote:

>  Is there a way to slice a string with a tuple without unpacking the tuple?
>
> >>> myString = "111-222-333-444"
> >>> myString[ 4: 7 ]
> '222'
>
> Is there some way I could perform an identical slicing operation with a
> tuple like ( 4, 7 ) without having to unpack the tuple?
>
> >>> myTuple = ( 4, 7 )
>
> Thanks!
> Malcolm
>

1) What's wrong with unpacking the tuple?

2) Use the built-in slice.

>>> myString = "111-222-333-444"
>>> myTuple = (4,7)
>>> mySlice = slice(*myTuple)
>>> myString[mySlice]
'222'
--
http://mail.python.org/mailman/listinfo/python-list


Possible to slice a string with unpacked tuple?

2009-01-24 Thread python
Is there a way to slice a string with a tuple without unpacking
the tuple?
>>> myString = "111-222-333-444"
>>> myString[ 4: 7 ]
'222'
Is there some way I could perform an identical slicing operation
with a tuple like ( 4, 7 ) without having to unpack the tuple?
>>> myTuple = ( 4, 7 )
Thanks!
Malcolm
--
http://mail.python.org/mailman/listinfo/python-list


Re: I'm a python addict !

2009-01-24 Thread Lie Ryan
On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote:

> I just started using python last week and I'm addicted.

you need to try this:

import antigravity

http://xkcd.com/353/

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


Re: Is there anyway Vpython and pyODE can be made to work with newer versions of Python 2.6.1 etc. without a lot of changes to source code?

2009-01-24 Thread Gerhard Häring

Casey Hawthorne wrote:

Is there anyway Vpython and pyODE can be made to work with newer
versions of Python 2.6.1 etc. without a lot of changes to source code?

I suppose I'm thinking of an extra layer of indirection, which might
slow things down to much.


Aren't this just Python libraries that include extension modules (i. e. 
modules written in C to interface external C libraries). If so, there is 
a good chance that just compiling them against Python 2.6 works out of 
the box. Otherwise the adjustments necessary will be just minor ones.


Python 3.0 compatibility is a different issue, though (more work).

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


Re: Dynamic methods and lambda functions

2009-01-24 Thread Michael Torrie
unine...@gmail.com wrote:
> The attributes are right, but the getter are not working. The problem
> is that the lambda function always execute the last parameter passed
> for all instances of the methods. How could it be done the right way?

Basically, don't use a lambda.  Create a real, local closure with a
nested def block.  That way the closure is created every time the parent
function is called.  Lambda expressions are only ever compiled once
during execution.

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


Re: Why GIL? (was Re: what's the point of rpython?)

2009-01-24 Thread Carl Banks
On Jan 24, 12:05 pm, Carl Banks  wrote:
> The default metatype for Python classes would be
> mutable_dict_type, which is a type wherein the object itself would be
> mutable but it would still have all the mutator methods __init__,
> __setattr__, etc., but they could only act on the __dict__.


Not wanting to risk confusion.

"The default metatype for Python classes would be mutable_dict_type,
which is a type wherein the object itself would be ***immutable*** but
it would still have all the mutator methods __init__, __setattr__,
etc., but they could only act on the __dict__."


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


Re: Why GIL?

2009-01-24 Thread Carl Banks
On Jan 24, 12:24 pm, Carl Banks  wrote:
> On Jan 24, 12:33 am, Hrvoje Niksic  wrote:
>
> > Carl Banks  writes:
> > > Anyway, all you're doing is distracting attention from my claim that
> > > instance objects wouldn't need to be locked.  They wouldn't, no
> > > matter how mutable you insist these objects whose bits would never
> > > change are.
>
> > Only if you're not implementing Python, but another language that
> > doesn't support __slots__ and assignment to instance.__dict__.
>
> I am only going to say all Python types prior to 3.0 support classes
> without __slots__,

I made a mistake, and I don't want to risk confusion at this point.

"all Python ***versions** prior to 3.0"

and I am talking about old-style classes, of course.  Prior to 2.2 no
classes at all supported slots.


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


Re: Why GIL?

2009-01-24 Thread Carl Banks
On Jan 24, 12:33 am, Hrvoje Niksic  wrote:
> Carl Banks  writes:
> > Anyway, all you're doing is distracting attention from my claim that
> > instance objects wouldn't need to be locked.  They wouldn't, no
> > matter how mutable you insist these objects whose bits would never
> > change are.
>
> Only if you're not implementing Python, but another language that
> doesn't support __slots__ and assignment to instance.__dict__.

I am only going to say all Python types prior to 3.0 support classes
without __slots__, so while I agree that this would be a different
language, it wouldn't necessarily be "not Python".

(Python, of course, is what GvR says Python is, and he isn't going to
say that the language I presented is Python.  No worries there! :)
I'm only saying that it is conceivably similar enough to be a
different version of Python.  It would be a different language in the
same way that Python 2.6 is a different language from Python 3.0.)

Incidentally, the proposal does allow slots to be defined, but only
for actual mutable types, not for ordinary class instances.


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


Regex for Python 2.7

2009-01-24 Thread MRAB

Some time ago I discovered this difference between regular expressions
in Python and Perl:

Python

\A matches at start of string
\Z matches at end of string

Perl

\A matches at start of string
\Z matches before terminal newline or at end of string
\z matches at end of string

In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^
and \Z != $ in single-string mode.

Obviously, changing Python's \Z to match Perl's could break existing
code. \z could be added, but with the opposite meaning to Perl's:

Python's \Z == Perl's \z
Python's \z == Perl's \Z

Would that be confusing?

Any suggests welcome.
--
http://mail.python.org/mailman/listinfo/python-list


Re: MaxInt on Vista-64bit?

2009-01-24 Thread googler . 1 . webmaster
Hi!

Thanks for the fast answer. Yes, its enough but I never thought that
Vista64 is not a real 64-bit operating system :-o.
--
http://mail.python.org/mailman/listinfo/python-list


Re: MaxInt on Vista-64bit?

2009-01-24 Thread Martin v. Löwis
> I downloaded Python64 for Windows Vista64 but the value returned from
> sys.maxint is just a 32bit integer. I found out, thats by design,
> Microsoft decided to make the long value 32bit. What can I do to
> compile python 2.6 with maxint of 64bit integers?

At a minimum, you need to change ob_ival to a 64-bit type in
PyIntObject. Consequentially, you probably need to change a lot
of other functions, e.g. PyInt_AsLong should probably also return
a 64-bit integer (as should PyInt_FromLong accept one). In turn,
you will need to change all callers of these functions to adjust
their parameter types. And so on.

> Can I replace the int values to a int64 value?

See above. In short: no. Use a real 64-bit operating system
(such as 64-bit Linux, Solaris, FreeBSD, etc)

Regards,
Martin

P.S. I do wonder why you want to do this, though. Isn't Python's
long integer type good enough?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why GIL? (was Re: what's the point of rpython?)

2009-01-24 Thread Carl Banks
On Jan 24, 12:40 am, "Gabriel Genellina" 
wrote:
> En Sat, 24 Jan 2009 06:06:02 -0200, Carl Banks   
> escribió:
>
>
>
> > On Jan 23, 11:45 pm, Bryan Olson  wrote:
> >> Carl Banks wrote:
> >> > Classes in Python are mutable types, usually.  Class instances are
> >> > (except for the refcount) immutable objects, usually.
>
> >> There's where we disagree. I assert that class instances are usually
> >> mutable objects.
>
> > Nope, you're dead wrong, nothing more to it.  The bits of a class
> > instance never change.  The __dict__ is a mutable object.  The class
> > instance itself isn't.  It's not reasonable to call an object whose
> > bits can't change a mutable obect.
>
> > Anyway, all you're doing is distracting attention from my claim that
> > instance objects wouldn't need to be locked.  They wouldn't, no matter
> > how mutable you insist these objects whose bits would never change
> > are.
>
> Me too, I don't get what you mean. Consider a list instance, it contains a  
> count of allocated elements, and a pointer to some memory block. They  
> change when the list is resized. This counts as "mutable" to me. I really  
> don't understand your claim.


Yeah, yeah, I know that, and in the bickering that ensued some aspects
of the original context were lost.  I should really not have been
pulled into Bryan's strawman over the definition of immutable, since
it's just a label, I oughtn't give a damn what it's called, I only
care what it does.  I didn't handle this repartee very well.

Anyway, it goes back to the original vision for a mark-and-sweep
Python language as I presented what seems like a long time ago.

I presented the type system that had three base metatypes instead of
the one base metatype we have now: immutable_type, mutable_type, and
mutable_dict_type.  The default metatype for Python classes would be
mutable_dict_type, which is a type wherein the object itself would be
mutable but it would still have all the mutator methods __init__,
__setattr__, etc., but they could only act on the __dict__.
mutable_dict_types would not be allowed to define any slots, and
__dict__ wouldn't be reassignable.  (However, it seems reasonable to
allow the base tp_new to accept a dict argument.)

OTOTH, list's metatype would be mutable_type, so the type object
itself would be mutable.

Bryan claimed that that would be a very different language from
Python, apparently because it hadn't occurred to him that by-and-
large, the instance itself doesn't change, only the dict does.
Perhaps Bryan was thinking of __dict__'s reassignability (that
certainly didn't occur to me); if he was I apologize for my snideness.

HAVING SAID THAT, I still still say what I proposed would not be a
radically different language from Python.  A little different, of
course.  Much slower, almost certainly.


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


Re: understanding nested lists?

2009-01-24 Thread Vincent Davis
Thanks for the info. I did not know that.
Thanks
Vincent Davis



On Sat, Jan 24, 2009 at 10:46 AM, Steve Holden  wrote:

> Vincent Davis wrote:
> > I have a short peace of code that is not doing what I expect. when I
> > assign a value to a list in a list alist[2][4]=z this seems replace all
> > the 4 elements in all the sub lists. I assume it is supposed to but this
> > is not what I expect. How would I assign a value to the 4th element in
> > the 2nd sublist. here is the code I have. All the printed values are
> > what I would expect except that all sublist values are replaced.
> >
> > Thanks for your help
> > Vincent
> >
> > on the first iteration I get ;
> > new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None],
> > [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None]]
> >
> > and expected this;
> > new_list [[None, 0, 1, None], [None, None, None, None],
> > [None, None, None, None], [None, None, None, None], [None, None, None,
> > None], [None, None, None, None]]
> >
> > Code;
> > list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]]
> > new_list=[[None]*4]*6
> > print 'new_list',new_list
> > for sublist in range(6): # 6 becuase it is the # of rows lists1
> > print 'sublist', sublist
> > for x in list1[sublist]:
> > print list1[sublist]
> > print 'new_list[sublist][x]', new_list[sublist][x]
> > new_list[sublist][x]=list1[sublist].index(x)
> > print 'sublist', sublist, 'x', x
> > print new_list[sublist][x]
> > print 'new_list', new_list
> >
> When you create new_list you are actually filling it with six references
> to the same list. Consequently when you change one of those list
> elements they all appear to change (because they are all referencing the
> same list object).
>
> Try instead
>
> new_list = [[None]*4 for i in range(6)]
>
> and you should find your code works as expected. In this case the list
> is constructed with a new sublist as each element.
>
> regards
>  Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


MaxInt on Vista-64bit?

2009-01-24 Thread googler . 1 . webmaster
Hi!

I downloaded Python64 for Windows Vista64 but the value returned from
sys.maxint is just a 32bit integer. I found out, thats by design,
Microsoft decided to make the long value 32bit. What can I do to
compile python 2.6 with maxint of 64bit integers?

Can I replace the int values to a int64 value?


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


Re: Byte oriented data types in python

2009-01-24 Thread skip

Ravi> packet_type (1 byte unsigned) || packet_length (1 byte unsigned) ||
Ravi> packet_data(variable)

Ravi> How to construct these using python data types, as int and float have
Ravi> no limits and their sizes are not well defined.

Take a look at the struct and ctypes modules.

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


Re: Byte oriented data types in python

2009-01-24 Thread Martin v. Löwis
> packet_type (1 byte unsigned) || packet_length (1 byte unsigned) ||
> packet_data(variable)
> 
> How to construct these using python data types, as int and float have
> no limits and their sizes are not well defined.

In Python 2.x, use the regular string type: chr(n) will create a single
byte, and the + operator will do the concatenation.

In Python 3.x, use the bytes type (bytes() instead of chr()).

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


Re: ossaudiodev problem: sawtooth noise

2009-01-24 Thread Peter Pearson
On Fri, 23 Jan 2009 14:55:36 -0200, Gabriel Genellina wrote:
> En Fri, 23 Jan 2009 14:36:46 -0200, Peter Pearson  
> escribió:
>> On Thu, 22 Jan 2009 20:58:14 -0200, Gabriel Genellina wrote:
>>> En Mon, 19 Jan 2009 21:57:04 -0200, Peter Pearson
>>>  escribió:
>>>
 The following code uses ossaudiodev to read 1000 values from
 my sound card at a rate of 12,000 samples per second:

 When I select a sample rate that is not a power of 2 times
 3000 samples/second, a strong and very regular sawtooth is
 superimposed on the signal.  At some sampling frequencies,
 it appears as a rising sawtooth, and at other sampling
 frequencies it is a declining sawtooth, so I'm presumably
 lost in some aliasing wilderness.  As best I can tell,
 it's a 48 KHz sawtooth.
>>>
>>> That could be a hardware and/or driver limitation. By example, an
>>> AC97-compliant chipset may provide a fixed rate of 48000 samples/second  
>>> any sample rate conversion must be done by other means, if possible at  
>>> all.
>>
>> Oh!  As a matter of fact, my "soundcard" *is* AC97-compliant
>> ("VT8233/A/8235/8237", according to Sysinfo).  So . . . this
>> sawtooth might result from some software, somewhere in the bucket
>> brigade between me and the hardware, attempting to perform
>> sample-rate conversion?  The 48 KHz coincidence seems very
>> significant.
>
> Yep. Google found this for me:
> http://mail-index.netbsd.org/port-i386/2003/02/18/0003.html
>
> Using a sample rate that is a sub-multiple of 48000 is perhaps a safe  
> approach.

Back around the time I installed Ubuntu's Hardy Heron, several
copies of this line appeared in /var/log/user.log.0:
Jan  4 21:32:53 eleodes pulseaudio[6437]: alsa-util.c: \
   Device front:0 doesn't support 44100 Hz, changed to 48000 Hz.

So I suppose I'll just restrict myself to well-behaved frequencies.
I'm not sure what "sub-multiple" means, but all the successful
frequencies I've found over 1 KHz have been multiples of 1.5 KHz that
evenly divide 48 KHz.  Frequencies showing large sawtooths include
2, 4, 8, 10, and 16 KHz.

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


Re: RegEx issues

2009-01-24 Thread MRAB

Roy Smith wrote:
[snip]

Another trick when you're not 100% what you're looking at is to
explode the string like this:


 [c for c in reg]
> ['\\', '[', '\\', '[', '(', '.', '*', ')', '\\', ']', '\\', ']', ';']
>
A shorter way is list(reg).
--
http://mail.python.org/mailman/listinfo/python-list


Re: TEST=`which test` equivalent in python?

2009-01-24 Thread Benjamin Kaplan
On Sat, Jan 24, 2009 at 2:03 PM, Jay Jesus Amorin wrote:

> Hi,
>
> Kindly help.
>
> import sys, os, string
>
> *SVNLOOK_PATH=os.system('which svnlook')*


Read the docs on os.system. It returns the program's return code, not the
child processes stdout. Use the subprocess module.

>
>
> def main(repos, txn):
> svnlook_cmd = '%s log -t "%s" "%s"' % (*SVNLOOK_PATH*, txn, repos)
> check_msg = os.popen(svnlook_cmd, 'r').readline().rstrip('\n')


os.popen does what you want here, but it is deprecated in favor of the more
powerful subprocess module.

>
>
> if len(check_msg) < 10:
> sys.stderr.write ("Blahh Blahh\n")
> sys.exit(1)
> else:
> sys.exit(0)
>
> if __name__ == '__main__':
> if len(sys.argv) < 3:
> sys.stderr.write("Usage: %s REPOS TXN\n" % (sys.argv[0]))
> else:
> main(sys.argv[1], sys.argv[2])
>
>
> The SVNLOOK_PATH is not working and python says its null when run as SVN
> hook-script. Do I need to load the os environment variable? How do i pass
> the value of 'which svnlook' to SVNLOOK_PATH variable.
>
> Thanks for your help.
>
>
> Jay
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Byte oriented data types in python

2009-01-24 Thread Stephen Hansen
I have following packet format which I have to send over Bluetooth.
>
> packet_type (1 byte unsigned) || packet_length (1 byte unsigned) ||
> packet_data(variable)
>
> How to construct these using python data types, as int and float have
> no limits and their sizes are not well defined.


Check out the struct module.

You want something like:

  data = struct.pack("BB4s", 1, 4, "this")

It returns a string of bytes according to the specification -- B is unsigned
byte, and "4s" is a string of 4 characters. The 1 feeds into the first byte,
the 4 into the second, etc.

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


Re: Parsing a string into a datetime object

2009-01-24 Thread Hrvoje Niksic
"Mark.Petrovic"  writes:

> Might someone comment on why %f is not accepted as a valid field
> directive in:
>
 from datetime import datetime
 created="2009-01-24 16:04:55.882788"
 dt = datetime.strptime(created,"%Y-%m-%d %H:%M:%S.%f")
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/
> python2.5/_strptime.py", line 321, in strptime
> (bad_directive, format))
> ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f'
>
> This is for Python 2.5.1 under OS X.

time.strptime is documented to use the same set of directives as
time.strftime, and
http://docs.python.org/library/time.html#time.strftime doesn't mention
a %f directive.
--
http://mail.python.org/mailman/listinfo/python-list


TEST=`which test` equivalent in python?

2009-01-24 Thread Jay Jesus Amorin
Hi,

Kindly help.

import sys, os, string

*SVNLOOK_PATH=os.system('which svnlook')*

def main(repos, txn):
svnlook_cmd = '%s log -t "%s" "%s"' % (*SVNLOOK_PATH*, txn, repos)
check_msg = os.popen(svnlook_cmd, 'r').readline().rstrip('\n')

if len(check_msg) < 10:
sys.stderr.write ("Blahh Blahh\n")
sys.exit(1)
else:
sys.exit(0)

if __name__ == '__main__':
if len(sys.argv) < 3:
sys.stderr.write("Usage: %s REPOS TXN\n" % (sys.argv[0]))
else:
main(sys.argv[1], sys.argv[2])


The SVNLOOK_PATH is not working and python says its null when run as SVN
hook-script. Do I need to load the os environment variable? How do i pass
the value of 'which svnlook' to SVNLOOK_PATH variable.

Thanks for your help.


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


Re: Porting 3.0 to 2.6 - from __future__ import super missing?

2009-01-24 Thread andrew cooke
On Jan 24, 2:32 pm, Benjamin Peterson  wrote:
> I would suggest that you use the 2.6 syntax, and run "2to3 -f metaclass" on 
> your
> code. (ABCs have been backported to 2.6.)

Thanks - with that hint I found this -
http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/#using-the-metaclass-in-python-2-x-and-3-x

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


Re: RegEx issues

2009-01-24 Thread Scott David Daniels

Sean Brown wrote:

I have the following string ...:  "td[ct] = [[ ... ]];\r\n"
The ... (representing text in the string) is what I'm extracting 
So I think the regex \[\[(.*)\]\]; should do it.
The problem is it appears that python is escaping the \ in the regex
because I see this:

reg = '\[\[(.*)\]\];'
reg

'\\[\\[(.*)\\]\\];'
Now to me looks like it would match the string - \[\[ ... \]\];
...


OK, you already have a good answer as to what is happening.
I'll mention that raw strings were put in the language exactly for
regex work.  They are useful for any time you need to use the backslash
character (\) within a string (but not as the final character).
For example:
len(r'\a\b\c\d\e\f\g\h') == 16 and len('\a\b\c\d\e\f\g\h') == 13

If you get in the habit of typing regex strings as r'...' or r"...",
and examining the patters with print(somestring), you'll ease your life.

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


Re: RegEx issues

2009-01-24 Thread Roy Smith
Sean Brown  wrote:

> The problem is it appears that python is escaping the \ in the regex
> because I see this:
> >>>reg = '\[\[(.*)\]\];'

The first trick of working with regexes in Python is to *always* use raw 
strings.  Instead of

reg = '\[\[(.*)\]\];'

you want

reg = r'\[\[(.*)\]\];'

In this case, I think it ends up not mattering, but it's one less thing to 
worry about.  Next, when looking at something like

> >>> reg
> '\\[\\[(.*)\\]\\];'

it's hard to see exactly what all the backslashes mean.  Which are real and 
which are escapes?  Try doing

>>> print reg
\[\[(.*)\]\];

which gets you the str(reg) instead of repr(reg).  Another trick when 
you're not 100% what you're looking at is to explode the string like this:

>>> [c for c in reg]
['\\', '[', '\\', '[', '(', '.', '*', ')', '\\', ']', '\\', ']', ';']
--
http://mail.python.org/mailman/listinfo/python-list


Byte oriented data types in python

2009-01-24 Thread Ravi
I have following packet format which I have to send over Bluetooth.

packet_type (1 byte unsigned) || packet_length (1 byte unsigned) ||
packet_data(variable)

How to construct these using python data types, as int and float have
no limits and their sizes are not well defined.
--
http://mail.python.org/mailman/listinfo/python-list


Re: RegEx issues

2009-01-24 Thread Steve Holden
Mark Tolonen wrote:
> 
> "Sean Brown"  wrote in message
> news:glflaj$qr...@nntp.motzarella.org...
>> Using python 2.4.4 on OpenSolaris 2008.11
>>
>> I have the following string created by opening a url that has the
>> following string in it:
>>
>> td[ct] = [[ ... ]];\r\n
>>
>> The ...  above is what I'm interested in extracting which is really a
>> whole bunch of text. So I think the regex \[\[(.*)\]\]; should do it.
>> The problem is it appears that python is escaping the \ in the regex
>> because I see this:
> reg = '\[\[(.*)\]\];'
> reg
>> '\\[\\[(.*)\\]\\];'
>>
>> Now to me looks like it would match the string - \[\[ ... \]\];
> 
> You are viewing the repr of the string
> 
 reg='\[\[(.*)\]\];'
 reg
> '\\[\\[(.*)\\]\\];'
 print reg
> \[\[(.*)\]\];<== these are the chars passed to regex
> 
> The slashes are telling regex the the [ are literal.
> 
>>
>> Which obviously doesn't match anything because there are no literal \ in
>> the above string. Leaving the \ out of the \[\[ above has re.compile
>> throw an error because [ is a special regex character. Which is why it
>> needs to be escaped in the first place.
>>
>> I am either doing something really wrong, which very possible, or I've
>> missed something obvious. Either way, I thought I'd ask why this isn't
>> working and why it seems to be changing my regex to something else.
> 
> Did you try it?
> 
 s='td[ct] = [[blah blah]];\r\n'
 re.search(reg,s).group(1)
> 'blah blah'
> 
Beware, though, that by default regex matches are greedy, so if there's
a chance that two [[ ... ]] [[ ... ]] can appear on the same line then
the above pattern will match

  ... ]] [[ ...

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

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


Re: Parsing a string into a datetime object

2009-01-24 Thread MRAB

Mark.Petrovic wrote:
> Good day.
>
> Might someone comment on why %f is not accepted as a valid field
> directive in:
>
 from datetime import datetime
 created="2009-01-24 16:04:55.882788"
 dt = datetime.strptime(created,"%Y-%m-%d %H:%M:%S.%f")
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/
> python2.5/_strptime.py", line 321, in strptime
> (bad_directive, format))
> ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f'
>
> This is for Python 2.5.1 under OS X.
>
> Thank you.
>
I believe that Python simply uses the 'strptime' (or equivalent)
function in the underlying C library: if that doesn't accept %f then
neither does Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Doc for extended call syntax; was: Re: unzip array of arrays?

2009-01-24 Thread Steve Holden
Bryan Olson wrote:
> Tobiah wrote:
>> Where can I read about
>> this mysterious use of the '*'?
> 
> Hmmm... that's a harder question than I thought. Am I missing it, or
> does Python's doc need a write-up of the extended call syntax?
> 
No, you aren't mistaken. Looking at the "*" symbol in the 2.6
documentation index it lists only two references. The first is the
language manual's explanation of its use in the def statement, the
second is a transitory reference to its use in function calls, but
that's in the tutorial where it is not likely to get much attention.

>> It only works in the
>> context of the zip() function.  It's hard to understand
>> how the interpreter handles that.
> 
> It works generally, for any callable. See the doc for 'apply':
> 
> http://docs.python.org/library/functions.html#non-essential-built-in-functions
> 
> 
> It not only works in a call, but also in function definitions. You can
> call a function with the extended call syntax whether or not is defined
> with * and ** arguments.
> 
> 
regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Web authentication urllib2

2009-01-24 Thread Scott David Daniels

Gabriel wrote:

Yep, i realize this a minute after posting, sorry.

And thank you again .)

Steve Holden wrote:

...

I'll offer a couple of pointers about what we all expect here.
Please treat this as advice, not a shout of disapproval.

(1) Do not top post (put your response above the previous interaction).
(2) When quoting previous interactions, cut until the portion you are
quoting provides enough context to make your post's context
comprehensible, but only that much context.
(3) When you figure out you problem, especially on your own, summarize
back in a final message what went wrong and how you fixed it.

The reasons for these three rules are:
(1) The message can be read in order, rather than reading up and down.
(2) People _do_ have access to the previous messages (albeit sometimes
only with some effort).  The message should be comprehensible on its
own, but your reader can go back for more detail if it turns out to
be vital.  You don't want to grow your message to the point where
someone who might help you says, "I don't have time to read that."
(3) Generally it is a good idea to search for answers before asking.
It can be incredibly frustrating to discover someone else had
previously seen exactly the same problem you are bashing your
head into the wall about, follow the chain, and finally read,
"Never mind, I figured it out." without a clue to what was
determined.

If you read comp.lang.python for a while, you'll see this is the
norm for messages here, and these behaviors help make this a more
pleasant place to read and write.

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


Re: What is intvar?

2009-01-24 Thread Steve Holden
W. eWatson wrote:
> W. eWatson wrote:
>> r wrote:
>>> here is a good explanation of control vars:
>>> http://infohost.nmt.edu/tcc/help/pubs/tkinter/control-variables.html
>>>
>>> Here are 3 great Tkinter refernces in order:
>>> http://infohost.nmt.edu/tcc/help/pubs/tkinter/
>>> http://effbot.org/tkinterbook/
>>> http://www.pythonware.com/library/tkinter/introduction/
>> Thanks to all for the reference and tips.
>>
> tkinterbook is easy to follow, but it seems to have been abandoned in
> 2005. Did it appear in another guise somewhere else?
> 
There hasn't been a lot of development on Tkinter in the intervening
period. It's a mature system, so there has been no need to update the
documentation.

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

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


Re: RegEx issues

2009-01-24 Thread Mark Tolonen


"Sean Brown"  wrote in message 
news:glflaj$qr...@nntp.motzarella.org...

Using python 2.4.4 on OpenSolaris 2008.11

I have the following string created by opening a url that has the
following string in it:

td[ct] = [[ ... ]];\r\n

The ...  above is what I'm interested in extracting which is really a
whole bunch of text. So I think the regex \[\[(.*)\]\]; should do it.
The problem is it appears that python is escaping the \ in the regex
because I see this:

reg = '\[\[(.*)\]\];'
reg

'\\[\\[(.*)\\]\\];'

Now to me looks like it would match the string - \[\[ ... \]\];


You are viewing the repr of the string


reg='\[\[(.*)\]\];'
reg

'\\[\\[(.*)\\]\\];'

print reg

\[\[(.*)\]\];<== these are the chars passed to regex

The slashes are telling regex the the [ are literal.



Which obviously doesn't match anything because there are no literal \ in
the above string. Leaving the \ out of the \[\[ above has re.compile
throw an error because [ is a special regex character. Which is why it
needs to be escaped in the first place.

I am either doing something really wrong, which very possible, or I've
missed something obvious. Either way, I thought I'd ask why this isn't
working and why it seems to be changing my regex to something else.


Did you try it?


s='td[ct] = [[blah blah]];\r\n'
re.search(reg,s).group(1)

'blah blah'

-Mark


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


Parsing a string into a datetime object

2009-01-24 Thread Mark.Petrovic
Good day.

Might someone comment on why %f is not accepted as a valid field
directive in:

>>> from datetime import datetime
>>> created="2009-01-24 16:04:55.882788"
>>> dt = datetime.strptime(created,"%Y-%m-%d %H:%M:%S.%f")
Traceback (most recent call last):
  File "", line 1, in 
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/_strptime.py", line 321, in strptime
(bad_directive, format))
ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f'

This is for Python 2.5.1 under OS X.

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


RegEx issues

2009-01-24 Thread Sean Brown

Using python 2.4.4 on OpenSolaris 2008.11

I have the following string created by opening a url that has the
following string in it:

td[ct] = [[ ... ]];\r\n

The ...  above is what I'm interested in extracting which is really a
whole bunch of text. So I think the regex \[\[(.*)\]\]; should do it.
The problem is it appears that python is escaping the \ in the regex
because I see this:

reg = '\[\[(.*)\]\];'
reg

'\\[\\[(.*)\\]\\];'

Now to me looks like it would match the string - \[\[ ... \]\];

Which obviously doesn't match anything because there are no literal \ in
the above string. Leaving the \ out of the \[\[ above has re.compile
throw an error because [ is a special regex character. Which is why it
needs to be escaped in the first place.

I am either doing something really wrong, which very possible, or I've
missed something obvious. Either way, I thought I'd ask why this isn't
working and why it seems to be changing my regex to something else.
--
http://mail.python.org/mailman/listinfo/python-list


Re: practical limits of urlopen()

2009-01-24 Thread Steve Holden
webcomm wrote:
> Hi,
> 
> Am I going to have problems if I use urlopen() in a loop to get data
> from 3000+ URLs?  There will be about 2KB of data on average at each
> URL.  I will probably run the script about twice per day.  Data from
> each URL will be saved to my database.
> 
> I'm asking because I've never opened that many URLs before in a loop.
> I'm just wondering if it will be particularly taxing for my server.
> Is it very uncommon to get data from so many URLs in a script?  I
> guess search spiders do it, so I should be able to as well?
> 
You shouldn't expect problem - though you might want to think about
using some more advanced technique like threading to get your results
more quickly.

This is Python, though. It shouldn't take long to write a test program
to verify that you can indeed spider 3,000 pages this way.

With about 2KB per page, you could probably build up a memory structure
containing the whole content of every page without memory usage becoming
too excessive for modern systems. If you are writing stuff out to a
database as you go and not retaining page content then there should be
no problems whatsoever.

Then look at a parallelized solution of some sort if you need it to work
more quickly.

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

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


Re: Two import questions in Python 3.0

2009-01-24 Thread Scott David Daniels

Kay Schluehr wrote:

On 24 Jan., 09:21, "Gabriel Genellina"  wrote:

If you run A.py as a script, it does not "know" it lives inside a package.
You must *import* A for it to become aware of the package.
Also, the directory containing the script comes earlier than PYTHONPATH
entries in sys.path -- so watch for that case too.

Thanks, yes. I always make the same error thinking that a directory
with the ritual __init__ file is actually a package ( as some kind of
platonic entity ), something that is more obvious to me than it is to
the runtime. The relative import semantics introduced with Python 2.5
has made the error just visible that was hidden to me for about a
decade. Shit.

Temper the language a bit.  You lose your effectiveness by some people
reading the color of your words, rather than their meaning in code.

By the way, if you run the script as:

$ python -m package.A

You may get what you want

demo (language fixed up a bit, moe info printed):

in .../lib/site-packages:
possible.py
-
print('import from top possible: %s' % __file__)

in .../lib/site-packages/package:
possible.py
-
print('import from package.possible: %s' % __file__)

__init__.py
-
print('package initialized: %s' % __file__)


A.py
--
print('A started: %s' % __file__)
import possible
print('A running: %s' % __file__)

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


Re: understanding nested lists?

2009-01-24 Thread Brian Allen Vanderburg II

vinc...@vincentdavis.net wrote:
I have a short peace of code that is not doing what I expect. when I 
assign a value to a list in a list alist[2][4]=z this seems replace 
all the 4 elements in all the sub lists. I assume it is supposed to 
but this is not what I expect. How would I assign a value to the 4th 
element in the 2nd sublist. here is the code I have. All the printed 
values are what I would expect except that all sublist values are 
replaced.


Thanks for your help
Vincent

on the first iteration I get ;
new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], 
[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None]]


and expected this;
new_list [[None, 0, 1, None], [None, None, None, None], 
[None, None, None, None], [None, None, None, None], [None, None, None, 
None], [None, None, None, None]]


Code;
list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]]
new_list=[[None]*4]*6
print 'new_list',new_list
for sublist in range(6): # 6 becuase it is the # of rows lists1
print 'sublist', sublist
for x in list1[sublist]:
print list1[sublist]
print 'new_list[sublist][x]', new_list[sublist][x]
new_list[sublist][x]=list1[sublist].index(x)
print 'sublist', sublist, 'x', x
print new_list[sublist][x]
print 'new_list', new_list



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


The problem is likely this right here:

[[None]*4]*6

This first creates an inner list that has 4 Nones, then the outer list 
contains 6 references to that same list, so (new_list[0] is new_list[1]) 
and (new_list[1] is new_list[2]).  I make this mistake a lot myself.


l=[[None]*4]*6
print id(l[0])  # -1210893364
print id(l[1])  # -1210893364

l = [list([None]*4) for x in range(6)]
print id(l[0])  # -1210893612
print id(l[1])  # -1210893580

Works better

Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: understanding nested lists?

2009-01-24 Thread Steve Holden
Vincent Davis wrote:
> I have a short peace of code that is not doing what I expect. when I
> assign a value to a list in a list alist[2][4]=z this seems replace all
> the 4 elements in all the sub lists. I assume it is supposed to but this
> is not what I expect. How would I assign a value to the 4th element in
> the 2nd sublist. here is the code I have. All the printed values are
> what I would expect except that all sublist values are replaced.
> 
> Thanks for your help
> Vincent
> 
> on the first iteration I get ;
> new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None],
> [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None]]
> 
> and expected this;
> new_list [[None, 0, 1, None], [None, None, None, None],
> [None, None, None, None], [None, None, None, None], [None, None, None,
> None], [None, None, None, None]]
> 
> Code;
> list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]]
> new_list=[[None]*4]*6
> print 'new_list',new_list
> for sublist in range(6): # 6 becuase it is the # of rows lists1
> print 'sublist', sublist
> for x in list1[sublist]:
> print list1[sublist]
> print 'new_list[sublist][x]', new_list[sublist][x]
> new_list[sublist][x]=list1[sublist].index(x)
> print 'sublist', sublist, 'x', x
> print new_list[sublist][x]
> print 'new_list', new_list
> 
When you create new_list you are actually filling it with six references
to the same list. Consequently when you change one of those list
elements they all appear to change (because they are all referencing the
same list object).

Try instead

new_list = [[None]*4 for i in range(6)]

and you should find your code works as expected. In this case the list
is constructed with a new sublist as each element.

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

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


Re: Web authentication urllib2

2009-01-24 Thread Steve Holden
Gabriel wrote:
> Yep, i realize this a minute after posting, sorry.
> 
> And thank you again .)
> 
A pleasure. Next time, you might consider posting an explanation along
with the "it's working now" message, just to give closure to the thread
for anyone who ends up reading it later after a search.

Good that you got your problem solved, anyway!

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

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


Re: Porting 3.0 to 2.6 - from __future__ import super missing?

2009-01-24 Thread Benjamin Peterson
andrew cooke  acooke.org> writes:
> Unfortunately, "metaclass=" is a syntax error in 2.6 so the following
> still fails:
> 
> from sys import version
> 
> if version.startswith('2.'):
> class Matcher():
> pass
> else:
> class Matcher(metaclass=ABCMeta):
> pass

I would suggest that you use the 2.6 syntax, and run "2to3 -f metaclass" on your
code. (ABCs have been backported to 2.6.)




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


practical limits of urlopen()

2009-01-24 Thread webcomm
Hi,

Am I going to have problems if I use urlopen() in a loop to get data
from 3000+ URLs?  There will be about 2KB of data on average at each
URL.  I will probably run the script about twice per day.  Data from
each URL will be saved to my database.

I'm asking because I've never opened that many URLs before in a loop.
I'm just wondering if it will be particularly taxing for my server.
Is it very uncommon to get data from so many URLs in a script?  I
guess search spiders do it, so I should be able to as well?

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


String comparision

2009-01-24 Thread S.Selvam Siva
Hi all,

I am developing spell checker for my local language(tamil) using python.
I need to generate alternative word list for a miss-spelled word from the
dictionary of words.The alternatives must be as much as closer to the
miss-spelled word.As we know, ordinary string comparison wont work here .
Any suggestion for this problem is welcome.

-- 
Yours,
S.Selvam
--
http://mail.python.org/mailman/listinfo/python-list


understanding nested lists?

2009-01-24 Thread Vincent Davis
I have a short peace of code that is not doing what I expect. when I assign
a value to a list in a list alist[2][4]=z this seems replace all the 4
elements in all the sub lists. I assume it is supposed to but this is not
what I expect. How would I assign a value to the 4th element in the 2nd
sublist. here is the code I have. All the printed values are what I would
expect except that all sublist values are replaced.
Thanks for your help
Vincent

on the first iteration I get ;
new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None,
0, 1, None], [None, 0, 1, None], [None, 0, 1, None]]

and expected this;
new_list [[None, 0, 1, None], [None, None, None, None], [None, None, None,
None], [None, None, None, None], [None, None, None, None],
[None, None, None, None]]

Code;
list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]]
new_list=[[None]*4]*6
print 'new_list',new_list
for sublist in range(6): # 6 becuase it is the # of rows lists1
print 'sublist', sublist
for x in list1[sublist]:
print list1[sublist]
print 'new_list[sublist][x]', new_list[sublist][x]
new_list[sublist][x]=list1[sublist].index(x)
print 'sublist', sublist, 'x', x
print new_list[sublist][x]
print 'new_list', new_list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mathematica 7 compares to other languages

2009-01-24 Thread Jerry Gerrone
On Jan 21, 1:06 pm, "soul.mirr...@gmail.com" 
wrote:
> On Dec 4 2008, 5:11 am, Andreas Waldenburger 
> wrote:
> > I vaguely remember you plonking [Xah Lee] before. Did you unplonk him in
> > the meantime? Or was that just a figure of speech?
>
> > teasingly yours,
> > /W
>
> Andreas Waldenburger, I hold up a mirror to your soul!
>
> A couple of years ago you started posting to the newsgroup
> comp.lang.java.programmer. Unlike most newbies, instead of lurking for
> a while and then contributing on-topic posts about Java, you jumped
> into the nearest available flamewar and immediately got in up to your
> neck. Then, on November 13, 2007, you stooped to intentionally
> misquoting one of your opponents. When he wrote
>
> http://groups.google.com/group/comp.lang.java.programmer/msg/7797d4e9...
>
> A few days later, you did it again, misquoting this post
>
> http://groups.google.com/group/comp.lang.java.programmer/msg/fca19d41...
>
> in this one:
>
> http://groups.google.com/group/comp.lang.java.programmer/msg/397e1d4b...
>
> In both cases, you publicly portrayed this poor man as a pervert, even
> though, whatever his other [insult deleted], that is clearly not one of
> them.

None of the nasty things that you have said or implied about me are at
all true.

> Repeatedly you have claimed to be primarily motivated by finding the
> disrupting of newsgroups to be entertaining. This is tantamount to
> admitting to being a troll.

Yes, and here you are, feeding him. Way to go, genius.

(And cljp had just gotten peaceful again, too!)
--
http://mail.python.org/mailman/listinfo/python-list


Doc for extended call syntax; was: Re: unzip array of arrays?

2009-01-24 Thread Bryan Olson

Tobiah wrote:

Where can I read about
this mysterious use of the '*'?


Hmmm... that's a harder question than I thought. Am I missing it, or 
does Python's doc need a write-up of the extended call syntax?



It only works in the
context of the zip() function.  It's hard to understand
how the interpreter handles that.


It works generally, for any callable. See the doc for 'apply':

http://docs.python.org/library/functions.html#non-essential-built-in-functions

It not only works in a call, but also in function definitions. You can 
call a function with the extended call syntax whether or not is defined 
with * and ** arguments.



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


Re: Counter Class -- Bag/Multiset

2009-01-24 Thread pataphor
On Thu, 22 Jan 2009 10:11:37 -0800 (PST)
Raymond Hettinger  wrote:

> The collections module in Python 2.7 and Python 3.1 has gotten a new
> Counter class that works like bags and multisets in other languages.

I like that! Now that we have a multiset or Counter I think a
redefinition of itertools.permutations is in order.

For example something like this:

def genperm(D, R = []):
#generate the permutations of a multiset
if not max(D.values()):
yield tuple(R)
else:
for k,v in sorted(D.items()):
if v: 
D[k] -= 1
for g in genperm(D,R+[k]): 
yield g
D[k] += 1

def perm(seq):
D = {}
for x in seq:
D[x] = D.get(x,0)+1
for X in genperm(D):
yield X

def test():
for i,x in enumerate(perm('aabbcc')):
print i,x
print len(set(perm('aabbcc')))

if __name__ == '__main__':
test()

The dictionary I'm using here could be seamlessly replaced by your
Counter class.

By the way, I like your itertools recipes a lot, but I miss something
that repeats elements n times, an xcycle or ncycle or whatever, like I
used in this (older code, sorry for the name overlap):

def repeat(x,n = 0):
i = 0
while i < n :
yield x
i += 1

def xcycle(seq,n):
while 1:
for x in seq:
for y in repeat(x,n):
yield y

def counter(symbols,width):
base = len(symbols)
R = []
k = width
while k:
k -= 1
R.append(xcycle(symbols,base**k))
nc = base**width
while nc:
yield list(x.next() for x in R)
nc -=1

def test():
symbols = '01'
width = 4
for state in counter(symbols,width):
print state

if __name__=='__main__':
test()

I think such a thing could be handy for generating more kinds of
periodic sequences. By the way, itertools is starting to feel like it's
becoming some sort of alternate programming design all by itself. I
wonder when it is going to break loose from python! I like that
way of thinking a lot, thanks.

P.

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


Re: OCaml, Language syntax, and Proof Systems

2009-01-24 Thread Joe Riopel
On Fri, Jan 23, 2009 at 6:16 PM, Xah Lee  wrote:
> The haskell tutorials you can find online are the most mothefucking
> stupid unreadable fuck. The Haskll community is almost stupid. What
> they talk all day is about monads, currying, linder myer fuck type.
> That's what they talk about all day. All day and night. Monad!  What's
> a monad! The importance of monad! How to learn monad! Simple intro to
> monad! Fucking morons, but MONAD!

http://www.youtube.com/watch?v=9fohXBj2UEI
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting 3.0 to 2.6 - from __future__ import super missing?

2009-01-24 Thread andrew cooke
On Jan 24, 10:39 am, Benjamin Peterson  wrote:
> andrew cooke  acooke.org> writes:
>
>
>
> > Hi,
>
> > I have some 3.0 code, which I would like to make work with 2.6.
> > However, there does not seem to be support for the new super() (no
> > args) via __future__.  Is that correct?  If so, what's the best way to
> > handle this?
>
> Just use the two argument super(): super(MyClass, instance) It's supported in
> both versions.

Thanks.  Any idea how to deal with ABCs?  It's sufficient to use a
simple class, but I want to expose an ABC in 3.0 as it will make it
easier for others to extend.

Unfortunately, "metaclass=" is a syntax error in 2.6 so the following
still fails:

from sys import version

if version.startswith('2.'):
class Matcher():
pass
else:
class Matcher(metaclass=ABCMeta):
pass

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


Re: What is intvar?

2009-01-24 Thread W. eWatson

W. eWatson wrote:

r wrote:

here is a good explanation of control vars:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/control-variables.html

Here are 3 great Tkinter refernces in order:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/
http://effbot.org/tkinterbook/
http://www.pythonware.com/library/tkinter/introduction/

Thanks to all for the reference and tips.

tkinterbook is easy to follow, but it seems to have been abandoned in 2005. 
Did it appear in another guise somewhere else?


--
   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: What's the business with the asterisk?

2009-01-24 Thread Kay Schluehr
On 24 Jan., 13:31, mk  wrote:
> Hello everyone,
>
>  From time to time I spot an asterisk (*) used in the Python code
> _outside_ the usual *args or **kwargs application.
>
> E.g. here:http://www.norvig.com/python-lisp.html
>
> def transpose (m):
>    return zip(*m)
>  >>> transpose([[1,2,3], [4,5,6]])
> [(1, 4), (2, 5), (3, 6)]
>
> What does *m mean in this example and how does it do the magic here?
>
> Regards,
> mk

If zip is specified as

def zip(*args):
...

one can pass zero or more arguments into zip. In the zip body one has
access to the argument tuple args. So zip(a, b, c) yields args = (a,
b, c). Now suppose you want to pass the tuple t = (a, b, c) to zip. If
you call zip(t) then args = ((a, b, c),). When calling zip(*t) instead
the tuple is passed as variable arguments just like they are specified
in the signature of zip. So args = (a, b, c).

Same holds for

def foo(**kwd):
...

and foo(**kwd) versus foo(kwd).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting 3.0 to 2.6 - from __future__ import super missing?

2009-01-24 Thread Benjamin Peterson
andrew cooke  acooke.org> writes:

> 
> Hi,
> 
> I have some 3.0 code, which I would like to make work with 2.6.
> However, there does not seem to be support for the new super() (no
> args) via __future__.  Is that correct?  If so, what's the best way to
> handle this?

Just use the two argument super(): super(MyClass, instance) It's supported in
both versions.




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


  1   2   >