Re: What would you like to see in a book about Matplotlib?

2009-01-11 Thread Sandro Tosi
Hello Marco,
thanks for your reply (and sorry for my late one)

On Jan 6, 9:26 am, Marco Nawijn  wrote:
> On Jan 5, 10:57 am, Sandro Tosi  wrote:
> I am happy to hear that there might be a book on Matplotlib. I am
> using Matplotlib for a while now and find it a very usefull and
> powerfull library for generating graphs. I will try to answer some of
> your questions. I am by no means an expert in the field, so I only
> express my personal experience.

And that's fine, because the audience of the book is people that have
never seen matplotlib and wanted to learn it.

> >> What are you using matplotlib for? I currently use Matplotlib to generate 
> >> a series of graphs that visualise data channels (strain measurements) 
> >> during a structural test. These graphs need to be refreshed about every 4 
> >> seconds. Each of the graphs contains 1 to 6 curves.

Just out of curiosity: how do you refresh those plots? in a loop
closing/opening the figure or clear the figure and replot on it? are
those graphs embedded in an application or are just "shown on screen"?

> >> What are the things you like the most of matplotlib, that you want
>
> to give emphasis to? And why? In general I like the most the fact that
> I can generate high quality publication ready graphs with a consistent
> look with minimal effort.

Indeed, that's one of the reason for its use in so many scientific
environments.

> Further, although the matlab-style commands
> are very usefull I think the class interface is more powerfull. The
> class interface also has a steeper learning curve. So, for me it would
> be very interesting if much emphasis will be on the class interface.

Yes, we will show the "class" interface during the examples, while
showing the difference just for the sake of completeness.

> >> What are the (basic) things that, when you were beginning to use
>
> matplotlib, you wanted to see grouped up but couldn't find? I
> seriously hope the book is not for "dummies",

as already said, this bug is intended to people that knows nothing
about mpl, so an introductory part will begin the book.

> but provides at least a
> significant amount of information on more advanced features of
> Matplotlib.

and we will try to show as much features as possible, even the
advanced one.

> I think the currently available tutorials are sufficient
> to getting started. From my point of view I am very interested in:
>     - Dynamically updating a series of graphs
>     - Configuring layout of graphs (colors, labels, legends, etc.)
>     - Managing dimensions of the figure when you export the figure to
> e.g PNG. For me this is interesting in the sense that if I insert a
> figure in a report/paper, I would like that the fonts used in the
> graph remain proportional to the surrounding text.

Those will be surely in the book :)

> If you need more information please let me know.

Well, whatever comes to mind, please let me know :)

> I wish you good luck!

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


Re: What would you like to see in a book about Matplotlib?

2009-01-11 Thread Dotan Cohen
2009/1/5 Sandro Tosi :
> Hello and Happy 2009!
>
> I received the interesting proposal to author a book on Matplotlib,
> the powerful 2D plotting library for Python.
>
> While preparing the arguments list, I'd like to hear even your
> opinion, because different points-of-view will lead to a better
> product.
>
> Some basic question I'd like to ask are:
>
> - what are you using matplotlib for?
> - what are the things you like the most of matplotlib, that you want
> to give emphasis to? And why?
> - what are the (basic) things that, when you were beginning to use
> matplotlib, you wanted to see grouped up but couldn't find?
> - what would you like to see in a book about matplotlib?
> - what are some those advanced feature that made you yell "WOW!!" ?
> - what are the things you'd like to explore of matplotlib and never
> had time to do?
>
> Your suggestions are really appreciated :) And wish me good luck!

I wish you good luck!

I would suggest at least a chapter on _acquiring_ the data that is to
be plotted using Python to scrape different sources _not_designed_ to
be scraped. Online webpages come to mind. An example on retrieving,
for instance, the prices of varying currencies, parsing the HTML
pages, extracting the data, and then plotting it would be a great
example for a real worlds usage that show matplotlib as a tool in a
toolchain, not a means to an end.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il

א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת
ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه‍-و-ي
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: What would you like to see in a book about Matplotlib?

2009-01-11 Thread Sandro Tosi
Hi James,
thanks for getting back to me.

On Jan 6, 9:33 am, James Stroud  wrote:
> Sandro Tosi wrote:
> > - what are the things you like the most of matplotlib, that you want
> > to give emphasis to? And why?
>
> The ability to embed a figure (composed of subplots) into a custom
> window is my favorite aspect.

Do you mean embed the figure in an application or simply a figure with
several subplots in it?

> Also: massive configurability of plots,
> event driven plot canvas, antigrain geometry antialiasing are also all
> very important. Additionally the toolbar of standard interactive
> functions and the ability to export plots in a variety of formats are
> also invaluable features.
>
> > - what are the (basic) things that, when you were beginning to use
> > matplotlib, you wanted to see grouped up but couldn't find?
>
> The documentation for basic plot configuration, especially for embedded
> plots, and also tapping into the event model is very weak currently.
> These need the most improvement.

What do you mean by "event model"?

> > - what would you like to see in a book about matplotlib?
>
> A big, huge, gigantic, chapter---no make that 3 chapters--on programming
>   interactivity with the plot canvas.

Big chapters a harder to read. And what exactly do you mean by
"interactivity"?

> > Your suggestions are really appreciated :) And wish me good luck!
>
> Good luck! I can't wait to read your book!

Thanks!

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


Re: Python strings and coding conventions

2009-01-11 Thread Marc 'BlackJack' Rintsch
On Sat, 10 Jan 2009 20:48:21 -0800, Mensanator wrote:

> Damn! I didn't know you could do that! And if I saw it in a program
> listing, such would never occur to me. I was going to suggest the stupid
> way:
> 
 ga = ['four score and seven years ago ', \
>   'our fathers brought forth ', \
>   'on this continent a new nation ', \
>   'conceived in liberty and dedicated ', \
>   'to the proposition that all men ', \
>   'are created equal']

What are all those line continuation characters ('\') for?  You are aware 
that they are unnecessary here?

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


Is negative seek() from EOF of a GzipFile supported on Python 2.5.2 ?

2009-01-11 Thread Barak, Ron
Hi Mark,

I googled a bit, and found http://bugs.python.org/issue1355023.
It seems that this patch implemented fuller seek() for GzipFile around November 
2006 (including whence==2).
Do I misunderstand and this patch was not actually implemented, namely, is 
seek(-n,2) not implemented in Python 2.5.2 ?

The source of gzip.py on my system seems to suggest that negative seeks are 
supported:

def seek(self, offset):
if self.mode == WRITE:
if offset < self.offset:
raise IOError('Negative seek in write mode')
count = offset - self.offset
for i in range(count // 1024):
self.write(1024 * '\0')
self.write((count % 1024) * '\0')
elif self.mode == READ:
if offset < self.offset:
# for negative seek, rewind and do positive seek
self.rewind()
count = offset - self.offset
for i in range(count // 1024):
self.read(1024)
self.read(count % 1024)

Could any who're familiar with the inner working of gzip settle this issue ?
Is seek from EOF supported for gzip files ?

Thanks,
Ron.

P.S.: as you guessed, my python 2.5.2 gives the not very helpful error:
Traceback (most recent call last):
  File "./_LogStream.py", line 53, in 
log_stream.last_line_loc_and_contents()
  File "./_LogStream.py", line 20, in last_line_loc_and_contents
self.input_file.seek(-1, 2) # grab the last character
TypeError: seek() takes exactly 2 arguments (3 given)

-Original Message-
From: Mark Tolonen [mailto:metolone+gm...@gmail.com]
Sent: Thursday, January 08, 2009 17:16
To: python-list@python.org
Subject: Re: Nubie question: how to not pass "self" in call to seek() function ?


"Barak, Ron"  wrote in message 
news:7f0503cd69378f49be0dc30661c6ccf602494...@enbmail01.lsi.com...
> Hi,
>
> I am getting the error TypeError: seek() takes exactly 2 arguments (3
> given), namely:
>
> $ ./_LogStream.py
> Traceback (most recent call last):
>   File "./_LogStream.py", line 47, in 
> log_stream.last_line_loc_and_contents()
>   File "./_LogStream.py", line 20, in last_line_loc_and_contents
> self.input_file.seek(-1, 2) # grab the last character
> TypeError: seek() takes exactly 2 arguments (3 given)
>
> When I run the below code.
>
> I understand that the extra argument is the "self", but I don't know
> how to change my class to make the seek(-1,2) work.
>
> Could you help ?

Perhaps the extra agrument is 2.  You don't mention your Python version, but in 
Python 2.6.1 gzip files don't support seeking from the end.  An older
(your?) version of Python may not be providing as helpful an error message.

>>> f=gzip.GzipFile('blah.gz','r')
>>> f.seek(-1,2)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\dev\python\lib\gzip.py", line 368, in seek
raise ValueError('Seek from end not supported')
ValueError: Seek from end not supported

-Mark


>
> Thanks,
> Ron.
>
> $ cat _LogStream.py
> #!/usr/bin/env python
>
> import gzip
> import sys
>
> from Debug import _line as line
>
> class LogStream():
>
> def __init__(self, filename):
> self.filename = filename
> self.input_file = self.open_file(filename)
> self.index_increment = 10
> self.last_line_offset = -1
>
> def last_line_loc_and_contents(self, estimated_line_size=1024):
>
> assert estimated_line_size > 0
> file_size = len(self.input_file.read())
> self.input_file.seek(-1, 2) # grab the last character
>
> if self.input_file.read(1) == '\n': # a "proper" text file
> file_size -= 1
>
> def open_file(self, in_file):
> """
> The gzip module checks if the input file is a gzipped file,
> only at the read stage.
> This is why the f.readline() is needed.
> """
> try:
> f = gzip.GzipFile(in_file, "r")
> f.readline()
> except IOError:
> f = open(in_file, "r")
> f.readline()
>
> f.seek(0)
> return(f)
>
>
> if __name__ == "__main__":
> filename =
> "../save_state/hp/save_state-ssp8400-0709R4_081126-121659/var/log\\sac.log.4.gz"
> log_stream = LogStream(filename)
> log_stream.limit_ = 1000
> log_stream.index_increment = 12
>
> log_stream.last_line_loc_and_contents()




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



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


Re: What would you like to see in a book about Matplotlib?

2009-01-11 Thread Sandro Tosi
Hello Thomas,
thanks for your reply.

On Jan 7, 5:11 pm, Thomas Guettler  wrote:
> Sandro Tosi schrieb:
> > - what are you using matplotlib for?
>
> I use the API to create PNGs from data stored in postgres. Webframework: 
> Django.

Nice, I plan to make some examples of web embedding of mpl, and one of
the frameworks is Django.

> > - what are the (basic) things that, when you were beginning to use
> > matplotlib, you wanted to see grouped up but couldn't find?
>
> The API is not good documented. It was very hard for me to understand
> what was going on the source.
>
> > - what would you like to see in a book about matplotlib?
>
> How to use the API.

Of course we will follow a gradual path, introducing simple apis and
then going deeper in the advanced features. So, if you mean API as
"pyplot.figure()" and so, they'll be covered :)

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


Re: What would you like to see in a book about Matplotlib?

2009-01-11 Thread Sandro Tosi
Hi Dotan,

On Jan 11, 10:02 am, "Dotan Cohen"  wrote:
> 2009/1/5 Sandro Tosi :
> > Your suggestions are really appreciated :) And wish me good luck!
>
> I wish you good luck!

Thanks you :)

> I would suggest at least a chapter on _acquiring_ the data that is to
> be plotted using Python to scrape different sources _not_designed_ to
> be scraped. Online webpages come to mind. An example on retrieving,
> for instance, the prices of varying currencies, parsing the HTML
> pages, extracting the data, and then plotting it would be a great
> example for a real worlds usage that show matplotlib as a tool in a
> toolchain, not a means to an end.

Well, a whole chapter to this is a little too much, but such examples
will be presented in the book: we're not going to teach how to program
in Python, but how to use matplotlib, so the data retriving is a
little out-of-scope (or at least border-line), so the code will be in
the examples provided along with the book, but not deeply explained in
the book text.

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


Bad hack fix around a bizarre problem...

2009-01-11 Thread Just Another Victim of the Ambient Morality
I'm trying to write a Python program that manipulates a MySQL database 
and have chosen to use MySQLdb.  So, I used by system's package manager, 
YUM, and it appeared to install correctly.  So, I tried it out and got this 
error:


Traceback (most recent call last):
  File "", line 1, in ?
  File "MySQLdb/__init__.py", line 22, in ?
raise ImportError, "this is MySQLdb version %s, but _mysql is version 
%r" %\
ImportError: this is MySQLdb version (1, 2, 2, 'final', 0), but _mysql is 
version (1, 2, 1, 'final', 1)


It looks like the MySQLdb version doesn't match the _mysql version.  If 
these were two different libraries, I might understand how this error 
happened.  However, they're part of the same library.  _mysql is just a 
Python binding to the MySQL C API and MySQLdb is just a Python wrapper 
around _mysql to be compliant with the Python DB specification.  They were 
both part of the same library so how did their versions fall out of sync? 
That's like getting a Windows application with incompatible DLLs!

So, my bad hack of a fix is to copy the MySQLdb python code to a local 
directory (where my python program will eventually reside) and, on this 
local copy, comment out the version check.  The idea is that MySQLdb is pure 
Python, so it's unlikely that there is any incompatibility between it and 
the very thin layer that is _mysql.  The local copy is so I don't forget 
that I'm using a modified version of this library.  Python seems to import 
this over the global one.  I've done a bit of testing and, so far, it 
appears to work!
What is my problem?  A google search reveals that I'm not the only 
person with this problem but it also reveals that absolutely no one knows 
how to fix this.  What are the chances that my fix will backfire?  Thank 
you... 


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


Re: Python strings and coding conventions

2009-01-11 Thread Ben Finney
Robert Kern  writes:

> I usually use implicit concatenation:
> 
> s = ('some long text that '
>  'needs to be split')

I do something very similar:

fleebnorg.spam = (
'some long text that'
' needs to be split')

The differences are:

I prefer to have indents as 4 spaces no matter how long the preceding
line is; but I also want the opening quote for the start of the string
to line up with subsequent open quotes for that string.

So I have all the portions of the string line up at the same (new)
indent level. To make that simpler without thinking about it every
time I change the first line, I simply break after the opening
parenthesis.

I prefer the continued portions to have the connecting space (or
whatever characters are contextually “connecting” in the text); this
is a greater visual cue that the string doesn't stand alone.

-- 
 \ “I went camping and borrowed a circus tent by mistake. I didn't |
  `\  notice until I got it set up. People complained because they |
_o__)   couldn't see the lake.” —Steven Wright |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-11 Thread Mark Wooding
ru...@yahoo.com  wrote:
> Mark Wooding wrote:
> > ru...@yahoo.com  wrote:
> >
> >> What is the observable difference between converting an
> >> array to a reference (pointer) to that array and passing
> >> the reference by value, and passing the array by reference?
> >
> > For one:
> >
> > #include 
> > static size_t foo(char v[]) { return sizeof v; }
> > int main(void) {
> >   char v[sizeof(char *) * 10];
> >   puts(foo(v) == sizeof(char *) ? "pointer" : "reference");
> >   return (0);
> > }
> 
> You are saying that because the size of the argument
> (10) is not available in the function, it cannot be
> call-by-reference?

No, I'm saying that because the parameter has pointer type, not array
type, it's a pointer being passed by value, not an array being passed by
reference.

And the size of the argument is not 10: it's 10 times as much as the
(nonzero) size of a pointer -- and therefore distinguishable on any C
implementation.

> I think fortran is accepted as the archetypal call-by-
> reference language and it does not automatically
> supply argument size information to functions.

Well and dandy; but Fortran doesn't turn arrays into pointers.

> > For another:
> >
> > static void bar(char v[]) { char ch = 0; v = &ch; }
> >   /* type error if arrays truly passed by reference */
> 
> v can be used as an array reference, e.g. "v[1] = 23"
> exactly as in the pass-by-reference fortran example.  And
> v can also be used as a local variable and reassigned.



> If the first option was the only one, would you not
> say C was definitely pass-by-reference (for arrays)?
> If one could only use v as a pointer (i.e. access
> the argument array as "*(v+1) = 23", then I would
> say that arrays are not passed at all, only pointers
> by-value.

Your knowledge of C is clearly limited, at best.  The notations *(p + i)
and p[i] are entirely equivalent in every way, since the square-brackets
indexing operator is in fact defined in terms of pointer dereference
(6.5.2.1):

: [#2] 2 A postfix expression followed by an expression in square
: brackets [] is a subscripted designation of an element of an array
: object. The definition of the subscript operator [] is that E1[E2] is
: identical to (*((E1)+(E2))). Because of the conversion rules that
: apply to the binary + operator, if E1 is an array object
: (equivalently, a pointer to the initial element of an array object)
: and E2 is an integer, E1[E2] designates the E2-th element of E1
: (counting from zero).

Of course, because the + operator is commutative

> That both these options exist causes me to conclude
> that, for arrays, parameter passing can be viewed
> as either arrays by-reference or pointers by-value.
> 
> I don't understand what relevance type checking
> has.  Since you are choosing to use v as a pointer,
> one would not expect a type error, yes?

Compare:

  void mumble(void) { char v[42]; char ch = 0; v = &ch; }
 /* error: incompatible types in assignment */

It's because in the previous case v is a pointer that the compiler
doesn't mind me assigning to it.  In this case, because it's an array,
the compiler objects.

> >> I guess the case for pass-by-value would be a little stronger because
> >> one has to have "passing a pointer by value" anyway (since pointers
> >> are first-class datatypes) and that can be used to describe passing
> >> arrays (as you described).
> >
> > The difference is that the /callee/ function is different between the
> > two cases.
> >
> > Also, notice that arrays in expressions turn into pointers in the same
> > way, so function argument passing works the same way as assignment -- a
> > hallmark of pass-by-value.
> 
> Not in all expressions as you yourself mentioned:
>  int a[10], *ap;
>  sizeof a;
>  sizeof ap;

Well done, you've pedantically picked up on the lapse in the first part
of the sentence (about sizeof, which as you say I've already mentioned
elsewhere) but failed to take any notice of the more important and
relevant point in the second half -- that argument passing works the
same way as assignment -- for `arrays' just as for other types.

void fa(char p[]);
void fp(char *p);
void fi(int i);

char a[10 * sizeof(char *)] = "bar", aa[10 * sizeof(char *)] = "splat";
char *p = "foo", *pp = "mumble";
int i = 42, ii = 69;

i = ii;   /* assignment of integers */
fi(ii);   /* integer call-by-value */

p = pp;   /* assignment of pointers */
fp(pp);   /* pointer call-by-value */
fa(pp);   /* pointer call-by-value again */

a = aa;   /* type error: incompatible types in assignment */
a = pp;   /* type error: incompatible types in assignment */
p = aa;   /* assignment of pointers */
fa(aa);   /* pointer call-by-value yet again */
fp(aa);   /* pointer call-by-value yet again */

Again, I refer readers to ISO 9899:1999: in particular:

  * 6.3.2.1p3 (array-to-pointer decay)
  * 6.5.2.2 (function calls)
  * 6.5.16 (assignment operator)

Since I'm getting thoroughly fed up of repeating myself on this point,
I'm simply going to assume, 

Re: Bad hack fix around a bizarre problem...

2009-01-11 Thread Diez B. Roggisch

Just Another Victim of the Ambient Morality schrieb:
I'm trying to write a Python program that manipulates a MySQL database 
and have chosen to use MySQLdb.  So, I used by system's package manager, 
YUM, and it appeared to install correctly.  So, I tried it out and got this 
error:



Traceback (most recent call last):
  File "", line 1, in ?
  File "MySQLdb/__init__.py", line 22, in ?
raise ImportError, "this is MySQLdb version %s, but _mysql is version 
%r" %\
ImportError: this is MySQLdb version (1, 2, 2, 'final', 0), but _mysql is 
version (1, 2, 1, 'final', 1)



It looks like the MySQLdb version doesn't match the _mysql version.  If 
these were two different libraries, I might understand how this error 
happened.  However, they're part of the same library.  _mysql is just a 
Python binding to the MySQL C API and MySQLdb is just a Python wrapper 
around _mysql to be compliant with the Python DB specification.  They were 
both part of the same library so how did their versions fall out of sync? 
That's like getting a Windows application with incompatible DLLs!


So, my bad hack of a fix is to copy the MySQLdb python code to a local 
directory (where my python program will eventually reside) and, on this 
local copy, comment out the version check.  The idea is that MySQLdb is pure 
Python, so it's unlikely that there is any incompatibility between it and 
the very thin layer that is _mysql.  The local copy is so I don't forget 
that I'm using a modified version of this library.  Python seems to import 
this over the global one.  I've done a bit of testing and, so far, it 
appears to work!
What is my problem?  A google search reveals that I'm not the only 
person with this problem but it also reveals that absolutely no one knows 
how to fix this.  What are the chances that my fix will backfire?  Thank 
you... 


I guess the package maintainer messed up. If you'd install MySQLdb from 
source, it won't happen I guess. So I'd contact the package maintainer.


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


Re: Python 2.6.1 @executable_path

2009-01-11 Thread googler . 1 . webmaster
Hi! :)

Thank you. I found PySys_SetPythonHome() to set the path where the lib
folder of Python is, but I guess they are not really implemented
because they are fixed compiled for an absolute path, aren't they?

Thats the whole problem. Do you have a suggestoin for the command line
how I can build it?


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


Re: Python 2.6.1 @executable_path

2009-01-11 Thread googler . 1 . webmaster
Thank you, I found PySys_SetPythonHome() to set the path where the lib
folder of Python is, but I guess they are not really implemented
because they are fixed compiled with an absolute path, aren't they?

Thats the problem. I hadn't compiled Python and I don't know if I
should
compile it as a dylib file or a framework? hmm. I know how to create a
framework but compiling as a dylib hadn't worked yet. :-(

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


Re: why cannot assign to function call

2009-01-11 Thread Aaron Brady
On Jan 10, 1:49 pm, Joe Strout  wrote:
> Aaron Brady wrote:
> >> Aaron Brady wrote:
> >>> Possible compromise.  You can think of functions as mutation-only.
> >>> You pass the object, and it gets a new (additional) name.  The old
> >>> name doesn't go in.  
> >> That's correct.  The reference itself is passed in, not the variable (or
> >> expression) that held or generated the reference in the calling code.
>
> > This is very odd, and I see it quite a bit.
> > Me: "You pass the object."
> > Joe: "That's correct.  You pass the reference."
>
> > What was wrong with my original?
>
> I'm saying that I believe your idea was correct, but worded imprecisely
> (IMHO of course).  So I restated what I believed you were saying, using
> terminology which I believe to be more precise.  If nothing else, this
> gives you the opportunity to say "No, that's not what I meant at all."

I believe that my summary is exceedingly beginner-oriented, you might
say colloquial.  Someone who has even a little programming experience
might find it childish.

> >> This is true.  (Technically, instead of variable, we should say "LValue"
> >> here -- there are things slightly more complex than simple variables
> >> that can serve as the left-hand side of an assignment.  So replace
> >> "variable" with "lvalue" above if you prefer.)
>
> > This is a point worth making.  I want to penny-pinch every term in an
> > introductory text, though, so, it's a tough call.
>
> Agreed.

Is a function call an lvalue in Python?  If not, descriptors are not
functions.

> >> M2: If 'fun()' returned a reference, you might be able to mutate the
> >> object that refers to.
> >> m2: You can sometimes mutate the object it refers to.
> >> C2: 'fun()' returns a reference.
>
> > This is horrendous.
> >http://en.wikipedia.org/wiki/Formal_fallacy
> >http://en.wikipedia.org/wiki/Affirming_the_consequent
>
> I did point out that the logic was incorrect (even though the
> conclusion, in this case, happens to be true).-

You've done nothing other than restate your claim; and worse, you
disguised doing so in the form of a deduction.

> > A question: Are you Joe and you Mark certain that the simplest
> > possible introductory explanation makes use of the term 'reference'?
>
> I am.

In any explanation, there is an amount of detail omitted.  In an
introduction, it's large.  (I hold false statements should be avoided,
of course, and even misleading ones.  However the latter is widely
subject-dependent.)  Your strategy may have a net positive unifying
power, though; and we should see it if so.  I may be asking whether it
is safe and prudent to avoid (introducing) the term at the level we're
looking at (as well as what level exactly it is).

> > Perhaps we can have a contest for shortest/simplest/best description
> > of Python's data/variable/argument model.
>
> Sure -- but it judging it might be difficult, requiring some newbies and
> a test to check their comprehension (as you and I pondered once before).

I think the step of least load would be to ask those who are having
difficulty what their background is.  At worst, they lie; next worst,
there's no pattern.

> > Lastly, I don't see any reason why we couldn't make both explanations
> > available.  'For those coming from Java/etc; for those coming from
> > C++/etc.'  They would both get read.
>
> Yes, except that the reference explanation applies equally well to
> anyone coming from Java, C/C++, RB, VB.NET, and probably others... I'm
> not sure to whom the other explanation would appeal, unless perhaps it's
> LISP programmers (just a guess, since those on that side of the aisle
> seem to invoke LISP more frequently).

True or not, it requires the reader to know what references are.  And,
since your definition conflicts with the C++ definition, it's not
clear that the requirement is good.

More terminology: is 'a' a variable, a reference, or an object, in
'a=2'?

It's a variable; it refers to an object.
It's a variable, which refers to an object.
It's a variable, which is a reference to an object.
It's a reference to an object.

Similarly, is '2' an expression, a reference, or an object?

It's an expression; it evaluates to an object.
It's an expression; it evaluates to a reference to an object.
It's an expression; it expresses an object.
It's an expression; it refers to an object.
It's a reference to an object.
It's an object.

I'd like to recommend we decide on unique answers, or avoid ambiguity
another way.


In the case of the Socratic, non-bludgeoning, dialogue with a student,
if the student can be trusted to question intelligently, s/he can be
expected, on our telling him/er, "'a' is an object", to ask, "What
object?"  Whether to expect audience interaction, and what
interaction, is a big component in the choice of method of a
demonstration.



>>> 300+301+302 is 300+301+302
False

There are 10 objects created in the evaluation of this, 11 if
including 'False'.  They (their integer contents), in order, are: 30

Re: if-else statement

2009-01-11 Thread Aaron Brady
On Jan 10, 2:28 pm, bearophileh...@lycos.com wrote:
> Scott David Daniels:
>
> >       if checking:
> >           my_var = 'string'
> >       else:
> >           my_var = 'other string'
>
> > remember, vertical space only kills trees if printed.
>
> I value clarity a lot. But this is more DRY, sometimes it's almost
> equally clear, and you reduce vertical space, packing more code in the
> same space, this allows you to see more logic, allowing you to have a
> higher level view of the code, so allows you to understand the code
> better:
>
> my_var = 'string' if checking else 'other string'
>
> So I think that sometimes it's useful.
>
> Bye,
> bearophile

It would be a good tool that allows you to see logic-- extra points
for dynamic!

A quick Google for 'python flow chart' turns up 'Visustin' (commercial
+ demo), 'Flowchart Python', & others.  
http://www.google.com/search?q=python+flow+chart
.  The "bird's eye view" in Visustin is pretty cool.

Control-flow-only could be a lot simpler, just filtering statements
with 'if/while/for', and try-except, not even in diagram.  It's on the
way for the open source IDE, right?
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-11 Thread Steven D'Aprano
On Sun, 11 Jan 2009 03:25:24 +, Mark Wooding wrote:

> Steven D'Aprano  wrote:
> 
>> I don't believe it is a red-herring. As I understand it, Mark and Joe
>> insist that C is pass-by-value *even in the case of arrays*, despite
>> the semantics of array passing being identical to the semantics of
>> pass-by- reference in (say) Pascal.
> 
> But they aren't.  I've provided several examples to show this.

Here's some p-b-r code in Pascal:


program main(input, output);
  type
arraytype = array[1..2] of integer;
  var
arr: arraytype;

procedure foo(var bar: arraytype);
  begin
bar[2] := 42;
writeln(' bar = ', bar[1], ' ', bar[2]);
  end;

begin
  arr[1] := 0;
  arr[2] := 0;
  writeln(' Before: arr = ', arr[1], ' ', arr[2]);
  foo(arr);
  writeln(' After: arr = ', arr[1], ' ', arr[2]);
end.


Here's the output from running that code:


 Before: arr = 0 0
 bar = 0 42
 After: arr = 0 42



Here's the equivalent C code, as close to an exact one-to-one 
correspondence as I can come up with:


#include

void foo(int bar[2])
{
  bar[1] = 42;
  printf("\n bar = %d %d ", bar[0], bar[1]);
}

int main()
{
int arr[2]={0,0};
printf("\n Before: arr = %d %d ", arr[0], arr[1]);
foo(arr);
printf("\n After: arr = %d %d ", arr[0], arr[1]);
printf("\n");
return 0;
}


And the output of it:

 Before: arr = 0 0
 bar = 0 42
 After: arr = 0 42


If it walks like pass-by-reference, and smells like pass-by-reference, 
and swims like pass-by-reference, is it still your contention that it is 
pass-by-value?



> For the purpose of clearing this up once and for all: arrays, in C, are
> `don't-pass-at-all'.  There is no way -- none whatever -- of declaring a
> function parameter as having array type.

It looks just like I did precisely that here:

void foo(int bar[2])

I guess this is where you explain again that arrays in C are "bizarre", 
and that while "int arr[2]" inside a function body means "declare an 
array of two ints and call it 'arr'", the exact same declaration in a 
function parameter list means something else. Possibly:

"Declare a pointer which points to an array of two ints, call the pointer 
'arr', and dereference the pointer every time it is used inside the 
function as if you were referring to the array directly".

Am I close?



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


Re: why cannot assign to function call

2009-01-11 Thread Paul Rubin
Steven D'Aprano  writes:
> If it walks like pass-by-reference, and smells like pass-by-reference, 
> and swims like pass-by-reference, is it still your contention that it is 
> pass-by-value?

Of course the C example is pass by value.  It's just that the value
being passed is an address.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regex for unicode letter characters

2009-01-11 Thread Steve Holden
MRAB wrote:
> Steve Holden wrote:
>> MRAB wrote:
>>> schickb wrote:
 I need a regex that will match strings containing only unicode letter
 characters (not including numeric or the _ character). I was surprised
 to find the 're' module does not include a special character class for
 this already (python 2.6). Or did I miss something?

 It seems like this would be a very common need. Is the following the
 only option to generate the character class (based on an old post by
 Martin v. Löwis )?

>>> [snip]
>>> Basically, yes.
>>>
>>> The re module was last worked on in 2003 (remember it's all voluntary!).
>>> Such omissions should be addressed in Python 2.7.
>>
>> By "should be" do you mean "ought to be (but I have no intention of
>> helping)", "are expected to be (but someone else will be doing the
>> work", "it's on my list and I am expecting to get finished in time for
>> 2.7 integration" or something else?
>>
> The third one.

Well, that's good news. Let me know if you need help.

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: Python strings and coding conventions

2009-01-11 Thread Steve Holden
Mensanator wrote:
> On Jan 10, 10:26�pm, Robert Kern  wrote:
>> koranth...@gmail.com wrote:
>>> Hi,
>>> � �Python Coding Convention (PEP 8) suggests :
>>> � Maximum Line Length
>>> � � Limit all lines to a maximum of 79 characters.
>>> � I have a string which is ~110 char long. It is a string which I am
>>> going to print in a text file as a single string.
>>> � i.e. in that text file, each line is taken as a different record -
>>> so it has to be in a single line.
>>> � Now, how can I write this code - while following PEP 8?
>>> � I tried blockstrings, but as shown in the example below:
>> s = r'''
>>> ... abcd
>>> ... efgh
>>> ... '''
>> s
>>> '\nabcd\nefgh\n'
>>> � �it has "\n" inserted - which will disallow printing it to a single
>>> line.
>>> � �I thought about other options like concatenating strings etc, but
>>> it seems very kludgy - esp since the whole string has a single meaning
>>> and cannot be easily split to many logically. Then I thought of
>>> creating a blockstring and then removing "\n", but it seemed
>>> kludgier...
>> I usually use implicit concatenation:
>>
>> s = ('some long text that '
>> � � � 'needs to be split')
> 
> Damn! I didn't know you could do that! And if I
> saw it in a program listing, such would never occur
> to me. I was going to suggest the stupid way:
> 
Another option is escaping the newlines in triple-quoted strings:

>>> s = """Some long text that \
... needs to be split"""
>>> s
'Some long text that needs to be split'
>>>

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: why cannot assign to function call

2009-01-11 Thread Aaron Brady
On Jan 11, 8:32 am, Paul Rubin  wrote:
> Steven D'Aprano  writes:
> > If it walks like pass-by-reference, and smells like pass-by-reference,
> > and swims like pass-by-reference, is it still your contention that it is
> > pass-by-value?
>
> Of course the C example is pass by value.  It's just that the value
> being passed is an address.

I believe, that in order for the C example to be p-b-r, you would need
the following:

void foo(var int bar[2])
{
  bar = malloc( something );
}

Such that the caller reflects the change.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python strings and coding conventions

2009-01-11 Thread MRAB

koranth...@gmail.com wrote:

On Jan 11, 9:26 am, Robert Kern  wrote:

koranth...@gmail.com wrote:

Hi,
   Python Coding Convention (PEP 8) suggests :
  Maximum Line Length
Limit all lines to a maximum of 79 characters.
  I have a string which is ~110 char long. It is a string which I am
going to print in a text file as a single string.
  i.e. in that text file, each line is taken as a different record -
so it has to be in a single line.
  Now, how can I write this code - while following PEP 8?
  I tried blockstrings, but as shown in the example below:

s = r'''

... abcd
... efgh
... '''

s

'\nabcd\nefgh\n'
   it has "\n" inserted - which will disallow printing it to a single
line.
   I thought about other options like concatenating strings etc, but
it seems very kludgy - esp since the whole string has a single meaning
and cannot be easily split to many logically. Then I thought of
creating a blockstring and then removing "\n", but it seemed
kludgier...

I usually use implicit concatenation:

s = ('some long text that '
  'needs to be split')

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


This is a very good method.
I found another method too - on further investigation

s = "abc\

... efg"

s

'abcefg'
Only problem being that it doesnt support indentation.
So, implicit concatenation it is...


Another possibility is continuation _plus_ implicit concatenation.

def example():
message = "now is the time " \
  "for all good people ..."
print message
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6.1 @executable_path

2009-01-11 Thread Michael Torrie
googler.1.webmas...@spamgourmet.com wrote:
> Thank you, I found PySys_SetPythonHome() to set the path where the lib
> folder of Python is, but I guess they are not really implemented
> because they are fixed compiled with an absolute path, aren't they?

I'm afraid I'm not following you here.  What is fixed compiled with an
absolute path?  What path are you talking about here?  Linker path?
Python default path for importing modules?

Please read the documentation on embedding python and you'll see that
you can initialize python and tell it to look anywhere for import
modules.  This is really all you have to do.  In fact, if you import the
built-in "sys" module, you can, from C++, add your Resource folder path
to the sys.path dictionary (using api calls) and dynamically affect
where python will import from.  I did this once when I had a case where
the user could place his plugin in an arbitrary spot.  Hence I had to
dynamically add the location to the path.

If you are embedding python in your app, I would expect you to be
familiar with the python apis.

> Thats the problem. I hadn't compiled Python and I don't know if I
> should
> compile it as a dylib file or a framework? hmm. I know how to create a
> framework but compiling as a dylib hadn't worked yet. :-(

I'm very confused as previously you were talking about compiling python
and now you're talking about not compiling python.  Although it doesn't
matter, since a framework file is a dylib file.

In any case if you don't know how to set the linker paths (to relative)
in App bundles, you'll want to consult apple docs, and the various apple
e-mail lists.


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


Re: why cannot assign to function call

2009-01-11 Thread Steven D'Aprano
On Sun, 11 Jan 2009 06:32:31 -0800, Paul Rubin wrote:

> Steven D'Aprano  writes:
>> If it walks like pass-by-reference, and smells like pass-by-reference,
>> and swims like pass-by-reference, is it still your contention that it
>> is pass-by-value?
> 
> Of course the C example is pass by value.  It's just that the value
> being passed is an address.

I believe that's exactly the way VAR (reference) parameters are 
implemented in Pascal. What's the difference?


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


Re: Python 2.6.1 @executable_path

2009-01-11 Thread googler . 1 . webmaster
yeap, okay, its just the beginning so I didn't know that the framework
is still the dylib file.
Well, I only want to compile python and put the framework in the
subdirectory. Thats all.
And the current state is, that the framework is not found because the
path of the compiled Python
library is hardcoded so when I move it from /Library/Frameworks/ to my
app folder it isn't found
when I start my app.

I found a ressource that I have to compile it with a dynamic path flag
like LDFLAGS="-install_name,@executable_path/../Frameworks" to put it
in the Framework of my app. maybe you know where my problem is. hm.

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


template inheritance

2009-01-11 Thread Alex K
While building a website using template inheritance one usually does
the following:

fetch from database
fetch from some more data from database
... << more required computations
then at the end render the template with the fetched data

Without template inheritance one usually does the following:

fetch from database
render this part of the site with this fetched data
fetch some more data from the database
render this other part of the site with the fetched data
...
etc

The first approach is much more elegant and leads to easier to
maintain code. However the user will have to wait till the end of the
fetching (long computations) before any rendering can take place. In
the second approach however the site loads as we are fetching the data
which is more convenient to the user.

Am I correct to assume this? Is there a way to get the best of both
worlds? Thank you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python strings and coding conventions

2009-01-11 Thread Mensanator
On Jan 11, 3:56�am, Marc 'BlackJack' Rintsch  wrote:
> On Sat, 10 Jan 2009 20:48:21 -0800, Mensanator wrote:
> > Damn! I didn't know you could do that! And if I saw it in a program
> > listing, such would never occur to me. I was going to suggest the stupid
> > way:
>
>  ga = ['four score and seven years ago ', \
> > � � � � � 'our fathers brought forth ', \
> > � � � � � 'on this continent a new nation ', \
> > � � � � � 'conceived in liberty and dedicated ', \
> > � � � � � 'to the proposition that all men ', \
> > � � � � � 'are created equal']
>
> What are all those line continuation characters ('\') for? �You are aware
> that they are unnecessary here?

Actually, I wasn't aware of that. A quick review shows
why. In the old manuals, implicit line continuation
was in a seperate chapter (2.1.6) from implicit (2.1.5)
so if you didn't read past 2.1.5 you would have missed it.

The 2.6 manual is much better in this regard as it is
now difficult to miss.

Thanks for pointing that out as lists are just about
the only place I use line continuation.

>
> Ciao,
> � � � � Marc 'BlackJack' Rintsch

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


Re: What would you like to see in a book about Matplotlib?

2009-01-11 Thread Dotan Cohen
2009/1/11 Sandro Tosi :
>> I would suggest at least a chapter on _acquiring_ the data that is to
>> be plotted using Python to scrape different sources _not_designed_ to
>> be scraped. Online webpages come to mind. An example on retrieving,
>> for instance, the prices of varying currencies, parsing the HTML
>> pages, extracting the data, and then plotting it would be a great
>> example for a real worlds usage that show matplotlib as a tool in a
>> toolchain, not a means to an end.
>
> Well, a whole chapter to this is a little too much, but such examples
> will be presented in the book: we're not going to teach how to program
> in Python, but how to use matplotlib, so the data retriving is a
> little out-of-scope (or at least border-line), so the code will be in
> the examples provided along with the book, but not deeply explained in
> the book text.
>

The problem with that approach is that you limit your audience to people who:
1) Are interested in matplotlab
-AND-
2) Are already familiar with Python

For every AND clause you remove you broaden the book's audience. You
do not need to rewrite the book on Python programming or programming
in general, but getting a C or even PHP programmer up to speed on the
basics of Python as related to matplotlib will make the book much more
accessible. At a minimum, it will add another valuable chapter to the
book that can be safely ignored by Python gurus. And you are making
the book that much more accessible.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il

א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת
ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه‍-و-ي
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python strings and coding conventions

2009-01-11 Thread Roy Smith
In article 
<5db6181f-d6f6-4bdc-88c8-e12ad228c...@r41g2000prr.googlegroups.com>,
 Mensanator  wrote:

> > What are all those line continuation characters ('\') for? ?You are aware
> > that they are unnecessary here?
> 
> Actually, I wasn't aware of that. A quick review shows
> why. In the old manuals, implicit line continuation
> was in a seperate chapter (2.1.6) from implicit (2.1.5)
> so if you didn't read past 2.1.5 you would have missed it.

My philosophy about line continuation is to assume lines can be continued 
after just about any piece of punctuation.  If I'm wrong, the computer will 
tell me, and then I make the computer happy by adding a \.  It's easier 
than looking it up, and way easier than memorizing the details.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-11 Thread Mark Wooding
Aaron Brady  wrote:

> True or not, it requires the reader to know what references are.  And,
> since your definition conflicts with the C++ definition, it's not
> clear that the requirement is good.

I blame C++ for coopting a perfectly good word with a established
well-understood meaning, and applying it to a half-baked and
inconsistent concept.

> More terminology: is 'a' a variable, a reference, or an object, in
> 'a=2'?
> 
> It's a variable; it refers to an object.
> It's a variable, which refers to an object.
> It's a variable, which is a reference to an object.
> It's a reference to an object.

It's an /identifier/ (2.3); or, if you want a shorter word, a /name/
(also 2.3).  (I'll go with `name'.)  In any given context, the name
might or might not mean something.  Names are assigned meanings by an
/environment/; if the environment assigns a meaning to a name, we say
that the name is /bound/ to that meaning; otherwise it is /unbound/.

The rules for determining the environment at any given point in a
program vary with language.  Python is fairly simple: it is /lexically
scoped/, which means that a great deal of information about the
environment can be determined simply by analysing the program text
statically.  (Compare `dynamic scope', where the environment at any
point in a program's executiondepends quite subtly on which functions
are active at that point.  The main difference is that, under lexical
scoping, a function's environment is an extension of the environment in
which it was defined, whereas under dynamic scoping a function's
environment is an extension of the environment of the caller.  Languages
can offer both kinds of scoping simultaneously: both Common Lisp and
Perl do this.)

Python is /block-structured/: various syntactic forms (/blocks/)
introduce new environments which are extensions of the environment of
the enclosing block, i.e., within the inner block, a few names are bound
to new meanings, while all the other names retain whatever meaning they
had in the enclosing block.  Names whose meanings are modified are said
to be /bound by the block/.  A name which occurs within the block is a
/bound occurrence/ if the name is bound by the block, or a /free
occurrence/ otherwise.

Python has what one might call `implicit binding': a name appearing
alone (or as part of a destructuring pattern) on the left-hand side of
an assignment which would otherwise be a free occurrence, and in the
absence of an explicit declaration such as `global' or `nonlocal', is
implicitly bound to a fresh variable by the smallest enclosing block.
Python also has explicit binding: e.g., the parameter names of a
function are explicitly bound to new variables by the function.

So, where were we?  `a = 2'.  The `a' is a name.  It appears alone on
the left-hand side of an assignment: this is therefore a candidate for
implicit binding.  Let's assume that `a' is bound to a variable, either
as a result of this or some other implicit binding, or an explicit
declaration.  (I don't believe Python has meanings other than variables
which might be bound to a name, so this is pretty safe.  Scheme, for
example, puts macros and special syntactic keywords in the same
namespace as variables, so you can, for example, lexically rebind the IF
keyword as a function, should you so wish.  This is probably a bad
idea.)

So, `a' is bound to a variable.  The variable, like all Python
variables, stores a reference.  We don't know what this reference might
be before the assignment, but afterwards, we know that it must be a
reference to an integer object representing the value 2.

This is cumbersome to talk about; in informal conversations, one often
talks about `the variable a' or even `the integer a'.  It's important to
realise that such phrases are abbreviations for convenience, and do not
directly correspond to reality.

> Similarly, is '2' an expression, a reference, or an object?
>
> It's an expression; it evaluates to an object.
> It's an expression; it evaluates to a reference to an object.
> It's an expression; it expresses an object.
> It's an expression; it refers to an object.
> It's a reference to an object.
> It's an object.

It's an /integer literal/ (2.4.3).  It's also an expression, because all
literals are expressions.  We can confidently predict that the value of
this expression (i.e., the result of evaluating it) is an integer object
representing the value 2.

> In the case of the Socratic, non-bludgeoning, dialogue with a student,
> if the student can be trusted to question intelligently, s/he can be
> expected, on our telling him/er, "'a' is an object", to ask, "What
> object?"  Whether to expect audience interaction, and what
> interaction, is a big component in the choice of method of a
> demonstration.

Declaring `a' to be an object begs many questions, such as `what type
does this object have?'.  This is an unfortunate question, because the
naive answer (e.g., from the above: `it's an integer') comes up against
the p

Re: Python strings and coding conventions

2009-01-11 Thread Mensanator
On Jan 11, 12:12�pm, Roy Smith  wrote:
> In article
> <5db6181f-d6f6-4bdc-88c8-e12ad228c...@r41g2000prr.googlegroups.com>,
>
> �Mensanator  wrote:
> > > What are all those line continuation characters ('\') for? ?You are aware
> > > that they are unnecessary here?
>
> > Actually, I wasn't aware of that. A quick review shows
> > why. In the old manuals, implicit line continuation
> > was in a seperate chapter (2.1.6) from implicit (2.1.5)
> > so if you didn't read past 2.1.5 you would have missed it.
>
> My philosophy about line continuation is to assume lines can be continued
> after just about any piece of punctuation. �If I'm wrong, the computer will
> tell me, and then I make the computer happy by adding a \. �It's easier
> than looking it up, and way easier than memorizing the details.

I proably got mine from Visual Basic where there are no
exceptions to explicit line continuation marks. A least
adding them when not necessary doesn't cause a problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-11 Thread Mark Wooding
Steven D'Aprano  wrote:

> I guess this is where you explain again that arrays in C are "bizarre", 
> and that while "int arr[2]" inside a function body means "declare an 
> array of two ints and call it 'arr'", the exact same declaration in a 
> function parameter list means something else. 

I quoted 6.7.5.3p7 before.  Please pay attention.

: A declaration of a parameter as ``array of type'' shall be adjusted to
: ``qualified pointer to type'', where the type qualifiers (if any) are
: those specified within the [ and ] of the array type derivation. If
: the keyword static also appears within the [and ] of the array type
: derivation, then for each call to the function, the value of the
: corresponding actual argument shall provide access to the first
: element of an array with at least as many elements as specified by the
: size expression.

> "Declare a pointer which points to an array of two ints, call the pointer 
> 'arr', and dereference the pointer every time it is used inside the 
> function as if you were referring to the array directly".

No.  Declare a pointer which points to an int, and call the pointer
`arr'.

> Am I close?

Vaguely.  A pointer to an array is not the same as a pointer to its
first element.  The former has type T (*)[N]; the latter has type T *.
The compiler entirely ignores the number (unless you write `static' --
little-known C99 feature).

There is no further magic: it's just a pointer.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Unbinding Tkinter default bindings for Listbox

2009-01-11 Thread Roger
Hi Everyone,

I have a behavior associated with a default binding with Tkinter
Listbox that I want to get rid of but I can't no matter if I return
"break" on the binding or unbind it directly. If you have a Listbox
where the bounding box is not completely revealed in the window that
holds it and you use the mouse to drag the list box, the contents of
the listbox will move in the X direction to reveal the area that's
hidden.  After searching the internet for hours I found the behavior I
want to remove is a default binding as described here:

http://tcltk.free.fr/man/TkCmd/listbox.php3

"[3] If the mouse leaves the listbox window with button 1 down, the
window scrolls away from the mouse, making information visible that
used to be off-screen on the side of the mouse. The scrolling
continues until the mouse re-enters the window, the button is
released, or the end of the listbox is reached. "

After further searching I found that the code for this in tcl is
described here:

http://www.openmash.org/lxr/source/library/listbox.tcl?c=tk8.3

 50 bind Listbox  {
 51 set tkPriv(x) %x
 52 set tkPriv(y) %y
 53 tkListboxMotion %W [%W index @%x,%y]
 54 }

Now I've found no way to successfully unbind B1-Motion from the
listbox, as I said above.  Nor return "break" on receiving the event.
I do want to eventually have my own B1-Motion binding applied to the
listbox for a different reason (with add='+' if necessary).  My next
step was to see if I could just unbind B1-Motion then programmatically
delete tkListboxMotion in my code but tkListboxMotion is not available
in the Tkinter source (it's part of a compiled binary I can't reach?).

Any help would be greatly appreciated.  Thanks!
Roger.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is negative seek() from EOF of a GzipFile supported on Python 2.5.2 ?

2009-01-11 Thread Mark Tolonen
"Barak, Ron"  wrote in message 
news:7f0503cd69378f49be0dc30661c6ccf602494...@enbmail01.lsi.com...
The source of gzip.py on my system seems to suggest that negative seeks 
are supported:


def seek(self, offset):
if self.mode == WRITE:
if offset < self.offset:
raise IOError('Negative seek in write mode')
count = offset - self.offset
for i in range(count // 1024):
self.write(1024 * '\0')
self.write((count % 1024) * '\0')
elif self.mode == READ:
if offset < self.offset:
# for negative seek, rewind and do positive seek
self.rewind()
count = offset - self.offset
for i in range(count // 1024):
self.read(1024)
self.read(count % 1024)

Could any who're familiar with the inner working of gzip settle this issue 
?

Is seek from EOF supported for gzip files ?


Source from 2.6.1.  Seek from EOF not supported:

   def seek(self, offset, whence=0):
   if whence:
   if whence == 1:
   offset = self.offset + offset
   else:
   raise ValueError('Seek from end not supported')
   if self.mode == WRITE:
   if offset < self.offset:
   raise IOError('Negative seek in write mode')
   count = offset - self.offset
   for i in range(count // 1024):
   self.write(1024 * '\0')
   self.write((count % 1024) * '\0')
   elif self.mode == READ:
   if offset < self.offset:
   # for negative seek, rewind and do positive seek
   self.rewind()
   count = offset - self.offset
   for i in range(count // 1024):
   self.read(1024)
   self.read(count % 1024)

-Mark


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


Re: What would you like to see in a book about Matplotlib?

2009-01-11 Thread Sandro Tosi
On Sun, Jan 11, 2009 at 18:50, Dotan Cohen  wrote:
> 2009/1/11 Sandro Tosi :
>>> I would suggest at least a chapter on _acquiring_ the data that is to
>>> be plotted using Python to scrape different sources _not_designed_ to
>>> be scraped. Online webpages come to mind. An example on retrieving,
>>> for instance, the prices of varying currencies, parsing the HTML
>>> pages, extracting the data, and then plotting it would be a great
>>> example for a real worlds usage that show matplotlib as a tool in a
>>> toolchain, not a means to an end.
>>
>> Well, a whole chapter to this is a little too much, but such examples
>> will be presented in the book: we're not going to teach how to program
>> in Python, but how to use matplotlib, so the data retriving is a
>> little out-of-scope (or at least border-line), so the code will be in
>> the examples provided along with the book, but not deeply explained in
>> the book text.
>
> The problem with that approach is that you limit your audience to people who:
> 1) Are interested in matplotlab
> -AND-
> 2) Are already familiar with Python

That is exactly the target the editor wants to reach...

> For every AND clause you remove you broaden the book's audience. You
> do not need to rewrite the book on Python programming or programming
> in general, but getting a C or even PHP programmer up to speed on the
> basics of Python as related to matplotlib will make the book much more
> accessible. At a minimum, it will add another valuable chapter to the
> book that can be safely ignored by Python gurus. And you are making
> the book that much more accessible.

I will try to ask this, but they were really clear that knowing python
is a prerequisite of the book readers.

-- 
Sandro Tosi (aka morph, morpheus, matrixhasu)
My website: http://matrixhasu.altervista.org/
Me at Debian: http://wiki.debian.org/SandroTosi
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-11 Thread rurpy
Mark Wooding wrote:
> ru...@yahoo.com  wrote:
>> Mark Wooding wrote:
>> > ru...@yahoo.com  wrote:
>...
>> > For another:
>> >
>> > static void bar(char v[]) { char ch = 0; v = &ch; }
>> >   /* type error if arrays truly passed by reference */
>>
>> v can be used as an array reference, e.g. "v[1] = 23"
>> exactly as in the pass-by-reference fortran example.  And
>> v can also be used as a local variable and reassigned.
>
>> If the first option was the only one, would you not
>> say C was definitely pass-by-reference (for arrays)?
>> If one could only use v as a pointer (i.e. access
>> the argument array as "*(v+1) = 23", then I would
>> say that arrays are not passed at all, only pointers
>> by-value.
>
> Your knowledge of C is clearly limited, at best.  The notations *(p + i)
> and p[i] are entirely equivalent in every way, since the square-brackets
> indexing operator is in fact defined in terms of pointer dereference
> (6.5.2.1):
>...

Yes, my C experience is limited.  I very rarely write
any C these days and even many years ago when I wrote
more, it was very vanilla stuff not requiring any deep
knowlage of dark corners of the language.

Nevertheless, I am aware of everything you wrote above
(the gist, not the standard's verbiage) and the common
demonstration of it: 3["surprised?"] => 'p'.

But if you'll note, I said "if ..." referring to a couple
of hypothetical C-like languages, so your chapter-and-verse
quote from the standard, while interesting and appreciated,
was basically irrelevant.

>...
>> > Also, notice that arrays in expressions turn into pointers in the same
>> > way, so function argument passing works the same way as assignment -- a
>> > hallmark of pass-by-value.
>>
>> Not in all expressions as you yourself mentioned:
>>  int a[10], *ap;
>>  sizeof a;
>>  sizeof ap;
>
> Well done, you've pedantically picked up on the lapse in the first part

It isn't pedantic.  It is the only thing (IFAIK) that
allows one to talk about variables of an array type (as
opposed to only pointers).

>...
> Since I'm getting thoroughly fed up of repeating myself on this point,
> I'm simply going to assume, from now on, that anyone who offers a
> disagreement without citing passages from (at least a specific draft of)
> ISO 9899 to support any claims made is simply being wilfully ignorant --
> and therefore no longer worth my attention.
>
> (If you don't have a copy of any such version, may I suggest
>
>   http://std.dkuug.dk/jtc1/sc22/open/n2794/
>
> citing this (confusingly) as n843, as a place to start.)

Actually I've already downloaded a C89/90 standard draft
in the hope that an earlier version would be simpler.
Since C's behavior vis "call-by-x" is (I presume) unchanged
back to K&R, whatever it said about it should be confirmable
by any ealier versions descriptions of C.

But more importantly, we seem to be talking at cross
purposes.

My idea of a language model is a description of the
language that is precise enough to allow a model's
user to predict how any piece of code will behave when
run.

The C-standard(s) do that for C.  Since many people
would claim that a language that does not behave as
the C standard describes is not C, it is definitional,
and one cannot reasonably say that the model presented
in the C standard is incorrect. (Of course, like all
standards, the C standard is not perfect, it contains
errors and inconsistencies that require correction,
and like all languages, C evolves requiring new versions
of the standard.)

Nevertheless, I see no reason to believe, based on
anything said in this thread, or my experience in
general, that there can be *only* one correct model
of a language, or part of a language.

So all the quoting of the C standard in the world
does not address the issue: can C's array passing be
described (modeled) as pass-by-reference?
I acknowledge that the C standard provides one
(correct) model in which arrays aren't passed, only
pointers by-value.

To address the issue you need to show that an alternate
model (array passing by-reference for example) is incorrect,
i.e. leads it user to conclude that a program will behave
differently than it does.  And of course, when such a
discrepancy model and behavior is pointed out, the proposer
of the alternate model will fix it if possible.

If you can not show that an alternate model is incorrect,
then the next best thing is to show that your model is
better.  Better would involve considerations such as simpler,
consistent with other languages, easier to understand by
various categories of users, etc.  Obviously this is a
very subjective task, and one could expect disagreement.

Many of the responses by you, Joe, and others, have
an "of course this model is the right one, how could
anyone think otherwise" tone to them.  I hope I have
explained clearly why I think that attitude is unjustified.

Finally, and please don't be insulted by this, but to
me and many readers, you are a bunch on glowing dots
on a screen.  I have been using the 

Re: template inheritance

2009-01-11 Thread Diez B. Roggisch

Alex K schrieb:

While building a website using template inheritance one usually does
the following:

fetch from database
fetch from some more data from database
... << more required computations
then at the end render the template with the fetched data

Without template inheritance one usually does the following:

fetch from database
render this part of the site with this fetched data
fetch some more data from the database
render this other part of the site with the fetched data
...
etc

The first approach is much more elegant and leads to easier to
maintain code. However the user will have to wait till the end of the
fetching (long computations) before any rendering can take place. In
the second approach however the site loads as we are fetching the data
which is more convenient to the user.

Am I correct to assume this? Is there a way to get the best of both
worlds? Thank you.


I don't think that the question of inheritance or not is really relevant 
here.


It's a matter of how the templating system is written - does it collect 
all the data beforehand, or not, is it potentially using e.g. generators 
and so forth.


And of course how the programmer uses the templating system. does he 
fetch all the data beforehand, or does he use lazy generation approachs 
- again, e.g. generators, or callbacks.


Besides, *usually* the 20-39Kb of a website itself aren't the problem 
I'd say - loading referenced resources is much more of an issue.


And AFAIK the render-mode matters, too. If the site is XHTML-compliant, 
the browser can start the rendering once the HTML is complete - 
otherwise, it might wait until the referenced resources are all loaded 
to calculate the layout.


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


Re: Python strings and coding conventions

2009-01-11 Thread John Machin
On Jan 12, 5:34 am, Mensanator  wrote:
> On Jan 11, 12:12 pm, Roy Smith  wrote:
>
>
>
>
>
> > In article
> > <5db6181f-d6f6-4bdc-88c8-e12ad228c...@r41g2000prr.googlegroups.com>,
>
> > Mensanator  wrote:
> > > > What are all those line continuation characters ('\') for? ?You are 
> > > > aware
> > > > that they are unnecessary here?
>
> > > Actually, I wasn't aware of that. A quick review shows
> > > why. In the old manuals, implicit line continuation
> > > was in a seperate chapter (2.1.6) from implicit (2.1.5)
> > > so if you didn't read past 2.1.5 you would have missed it.
>
> > My philosophy about line continuation is to assume lines can be continued
> > after just about any piece of punctuation. If I'm wrong, the computer will
> > tell me, and then I make the computer happy by adding a \. It's easier
> > than looking it up, and way easier than memorizing the details.
>
> I proably got mine from Visual Basic where there are no
> exceptions to explicit line continuation marks. A least
> adding them when not necessary doesn't cause a problem.

Fugly code is not a problem?
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-11 Thread Mark Wooding
ru...@yahoo.com  wrote:

> But if you'll note, I said "if ..." referring to a couple of
> hypothetical C-like languages, so your chapter-and-verse quote from
> the standard, while interesting and appreciated, was basically
> irrelevant.

Ah, what you actually said was still quoted above (thanks):

: v can be used as an array reference, e.g. "v[1] = 23" exactly as in
: the pass-by-reference fortran example.  And v can also be used as a
: local variable and reassigned.
: 
: If the first option was the only one, would you not say C was
: definitely pass-by-reference (for arrays)?

I must have been reading too quickly and I missed the conditional here.
I'm terribly sorry. :-(

Answering the question as posed, rather than mis-read: I think the
sizeof business would still indicate that a pointer was being passed.

If the language also forbade sizeof on array-type arguments and passing
array as arguments to functions expecting pointers, then I'd say you'd
have a point.  But I'm not sure I'd agree that such a language was
`C-like' -- the bizarre behaviour of arrays is one of the language's
most distinctive features!

> >> > Also, notice that arrays in expressions turn into pointers in the same
> >> > way, so function argument passing works the same way as assignment -- a
> >> > hallmark of pass-by-value.
> >>
> >> Not in all expressions as you yourself mentioned:
> >>  int a[10], *ap;
> >>  sizeof a;
> >>  sizeof ap;
> >
> > Well done, you've pedantically picked up on the lapse in the first part
> 
> It isn't pedantic.  It is the only thing (IFAIK) that allows one to
> talk about variables of an array type (as opposed to only pointers).

You can talk about /variables/ of array type, but not /expressions/ of
array type (except in very limited circumstances, as operands of sizeof
or &).

> Actually I've already downloaded a C89/90 standard draft in the hope
> that an earlier version would be simpler.  Since C's behavior vis
> "call-by-x" is (I presume) unchanged back to K&R, whatever it said
> about it should be confirmable by any ealier versions descriptions of
> C.

It should be; but you may have to adjust the clause numbers I'm citing.
Also, the earlier version of the standard didn't have numbered
paragraphs, which makes citing specific bits more tedious.

> But more importantly, we seem to be talking at cross purposes.

We might be...

[snip]

> So all the quoting of the C standard in the world does not address the
> issue: can C's array passing be described (modeled) as
> pass-by-reference?  I acknowledge that the C standard provides one
> (correct) model in which arrays aren't passed, only pointers by-value.
>
> To address the issue you need to show that an alternate model (array
> passing by-reference for example) is incorrect, i.e. leads it user to
> conclude that a program will behave differently than it does.  And of
> course, when such a discrepancy model and behavior is pointed out, the
> proposer of the alternate model will fix it if possible.

I'd claim, in fact, that the proposer of an alternative model bears the
responsibility to prove it correct, i.e., in the case of C, at least
consistent with the official standard.

But I believe that I have indeed shown that the arrays-passed-by-
reference model is incorrect, by demonstrating that the called function
sees the parameter as a freshly allocated pointer and not an array: it
can be assigned (unlike an array); its size is that of a pointer; one
can take its address and manipulate its bit-pattern as if it were a
pointer.  Indeed, the standard guarantees that no strictly-conforming C
program can distinguish the parameter from a freshly allocated pointer.

And therefore I can point to my earlier (almost-formal) definitions of
pass-by-value and pass-by-reference to complete the proof: the
allocation of a new variable is inconsistent with pass-by-reference,
while it is consistent with pointer-decay followed by pass-by-value.

Of course, this is contingent on your acceptance of my definitions.  But
I don't see anyone else providing sufficiently detailed definitions to
make such proofs, and my definitions seem consistent with the way most
other languages use the terms, so I'm pretty confident that they're
good...

> Many of the responses by you, Joe, and others, have an "of course this
> model is the right one, how could anyone think otherwise" tone to
> them.  I hope I have explained clearly why I think that attitude is
> unjustified.

I hope that I've been doing more than that: drawing comparisons with and
borrowing concepts from other languages, attempting to solidify
definitions which otherwise seem to cause controversy, and then drawing
conclusions from these definitions to strengthen my case and weaken
others' cases.

> Finally, and please don't be insulted by this, but to me and many
> readers, you are a bunch on glowing dots on a screen.

As are we all.  (Brought to you by Sobering Thought for the Day.)

> I have been using the internet long enough to

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

2009-01-11 Thread Madhusudan.C.S
  I am sorry all I am not here to just blame Python. This is just an
introspection of whether
what I believe is right. Being a devotee of Python from past 2 years I
have been writing only
small apps and singing praises about Python where ever I go. I now got
a chance to read
Django's code for some reason. I have now strongly started feeling if
Python really follows its
"Readability Counts" philosophy. For example,

class A:
a = 10
b = "Madhu"

def somemethod(self, arg1):
self.c = 20.22
d = "some local variable"
# do something

...
def somemethod2 (self, arg2):
self.c = "Changed the variable"
# do something 2
...

In such situations, where the Instance variables come into existence
only when they are used
it is very difficult to track the flow of code. Its obviously not
possible to remember what
instance variable was defined where, when reading some substantial
amount of code and where
it was manipulated for that matter. It becomes so very frustrating
even when reading a Class's
code with just 6-8 methods and not more than 100-150 lines of code.

I am interested in knowing if I am reading this kind of code in the
wrong way mostly because
of C++/Java hangover since most other languages follow the same
approach as them? If there
is a Pythonic way reading this code for better readability? What made
Python developers to
adopt this strange strategy keeping "Readibility Counts" in mind?

-- Python Rocks!
   Madhusudan.C.S
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python strings and coding conventions

2009-01-11 Thread Mensanator
On Jan 11, 2:37�pm, John Machin  wrote:
> On Jan 12, 5:34�am, Mensanator  wrote:
>
>
>
>
>
> > On Jan 11, 12:12 pm, Roy Smith  wrote:
>
> > > In article
> > > <5db6181f-d6f6-4bdc-88c8-e12ad228c...@r41g2000prr.googlegroups.com>,
>
> > > Mensanator  wrote:
> > > > > What are all those line continuation characters ('\') for? ?You are 
> > > > > aware
> > > > > that they are unnecessary here?
>
> > > > Actually, I wasn't aware of that. A quick review shows
> > > > why. In the old manuals, implicit line continuation
> > > > was in a seperate chapter (2.1.6) from implicit (2.1.5)
> > > > so if you didn't read past 2.1.5 you would have missed it.
>
> > > My philosophy about line continuation is to assume lines can be continued
> > > after just about any piece of punctuation. If I'm wrong, the computer will
> > > tell me, and then I make the computer happy by adding a \. It's easier
> > > than looking it up, and way easier than memorizing the details.
>
> > I proably got mine from Visual Basic where there are no
> > exceptions to explicit line continuation marks. A least
> > adding them when not necessary doesn't cause a problem.
>
> Fugly code is not a problem?

Is that how you justify breaing "explicit is
better than implicit"?


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


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

2009-01-11 Thread Chris Rebert
On Sun, Jan 11, 2009 at 1:22 PM, Madhusudan.C.S  wrote:
>  I am sorry all I am not here to just blame Python. This is just an
> introspection of whether
> what I believe is right. Being a devotee of Python from past 2 years I
> have been writing only
> small apps and singing praises about Python where ever I go. I now got
> a chance to read
> Django's code for some reason. I have now strongly started feeling if
> Python really follows its
> "Readability Counts" philosophy. For example,
>
>class A:
>a = 10
>b = "Madhu"

Those are class variables, not instance variables. There is a distinct
difference. Instance variables, in contrast, are "declared" and
created in the body of the __init__ method.

>
>def somemethod(self, arg1):
>self.c = 20.22
>d = "some local variable"
># do something
>
>...
>def somemethod2 (self, arg2):
>self.c = "Changed the variable"
># do something 2
>...
>
> In such situations, where the Instance variables come into existence
> only when they are used
> it is very difficult to track the flow of code. Its obviously not
> possible to remember what
> instance variable was defined where, when reading some substantial
> amount of code and where
> it was manipulated for that matter. It becomes so very frustrating
> even when reading a Class's
> code with just 6-8 methods and not more than 100-150 lines of code.

That's bad coding style on the part of the code writer.
Conditionally-existing instance variables are *evil*.

Cheers,
Chris

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


Re: Python strings and coding conventions

2009-01-11 Thread John Machin
On Jan 12, 8:23 am, Mensanator  wrote:
> On Jan 11, 2:37 pm, John Machin  wrote:
>
>
>
>
>
> > On Jan 12, 5:34 am, Mensanator  wrote:
>
> > > On Jan 11, 12:12 pm, Roy Smith  wrote:
>
> > > > In article
> > > > <5db6181f-d6f6-4bdc-88c8-e12ad228c...@r41g2000prr.googlegroups.com>,
>
> > > > Mensanator  wrote:
> > > > > > What are all those line continuation characters ('\') for? ?You are 
> > > > > > aware
> > > > > > that they are unnecessary here?
>
> > > > > Actually, I wasn't aware of that. A quick review shows
> > > > > why. In the old manuals, implicit line continuation
> > > > > was in a seperate chapter (2.1.6) from implicit (2.1.5)
> > > > > so if you didn't read past 2.1.5 you would have missed it.
>
> > > > My philosophy about line continuation is to assume lines can be 
> > > > continued
> > > > after just about any piece of punctuation. If I'm wrong, the computer 
> > > > will
> > > > tell me, and then I make the computer happy by adding a \. It's easier
> > > > than looking it up, and way easier than memorizing the details.
>
> > > I proably got mine from Visual Basic where there are no
> > > exceptions to explicit line continuation marks. A least
> > > adding them when not necessary doesn't cause a problem.
>
> > Fugly code is not a problem?
>
> Is that how you justify breaing "explicit is
> better than implicit"?

I don't '''justify breaing "explicit is better than implicit"''' and
wasn't attempting to do so.

The Zen is more than one saying. No one saying trumps all others. Some
may appear to be in conflict with others. One must consider the
combined effect. Other sayings relevant to your problem are:

Beautiful is better than ugly.
Simple is better than complex.
Readability counts.

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


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

2009-01-11 Thread BJörn Lindqvist
2009/1/11 Madhusudan.C.S :
> Django's code for some reason. I have now strongly started feeling if
> Python really follows its
> "Readability Counts" philosophy. For example,
>
>class A:
>a = 10
>b = "Madhu"
>
>def somemethod(self, arg1):
>self.c = 20.22
>d = "some local variable"
># do something
>
>...
>def somemethod2 (self, arg2):
>self.c = "Changed the variable"
># do something 2
>...

In this case is the "c" attribute not "declared" in the __init__() method of A?

> I am interested in knowing if I am reading this kind of code in the
> wrong way mostly because
> of C++/Java hangover since most other languages follow the same
> approach as them? If there
> is a Pythonic way reading this code for better readability? What made
> Python developers to
> adopt this strange strategy keeping "Readibility Counts" in mind?

Not declaring instance variables is just poor form. IMHO Python code
should mostly be written like C++/Java. When you use "tricks" like the
above (dynamically adding attributes to a class) or getattr calls,
catching AttributeErrors, manipulating __dict__, decorators or
metaclasses you should really think twice whether you actually _need_
to use those tricks.


-- 
mvh Björn
--
http://mail.python.org/mailman/listinfo/python-list


Object help

2009-01-11 Thread killsto
I have a class called ball. The members are things like position,
size, active. So each ball is an object.

How do I make the object without specifically saying ball1 = ball()?
Because I don't know how many balls I want; each time it is different.

The balls are to be thrown in from the outside of the screen. I think
you get that is enough information.

This doesn't directly pertain to balls, I have wanted to do something
like this for many different things but didn't know how.

I would think something like:

def newball():
 x = last_named_ball + 1
ball_x = ball(size, etc) # this initializes a new ball
return ball_x

But then that would just name a ball ball_x, not ball_1 or ball_2.

Is it possible?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Object help

2009-01-11 Thread Chris Rebert
On Sun, Jan 11, 2009 at 2:06 PM, killsto  wrote:
> I have a class called ball. The members are things like position,
> size, active. So each ball is an object.

Class names should use CamelCase, so it should be `Ball`, not `ball`.

> How do I make the object without specifically saying ball1 = ball()?
> Because I don't know how many balls I want; each time it is different.
>
> The balls are to be thrown in from the outside of the screen. I think
> you get that is enough information.
>
> This doesn't directly pertain to balls, I have wanted to do something
> like this for many different things but didn't know how.
>
> I would think something like:
>
> def newball():
> x = last_named_ball + 1
>ball_x = ball(size, etc) # this initializes a new ball
>return ball_x
>
> But then that would just name a ball ball_x, not ball_1 or ball_2.
>
> Is it possible?

Yes, but only using deep dark black magic. Just use a list of Ball
objects instead.

Example:
the_balls = [Ball(size, etc) for i in range(number_of_balls)]

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


Re: Object help

2009-01-11 Thread Jervis Whitley
On Mon, Jan 12, 2009 at 9:06 AM, killsto  wrote:

>
> I would think something like:
>
> def newball():
> x = last_named_ball + 1
>ball_x = ball(size, etc) # this initializes a new ball
>return ball_x
>
> But then that would just name a ball ball_x, not ball_1 or ball_2.
>
> Is it possible?
>
>
How about placing the balls in a python list:balls = [Ball() for i in
range(number_of_balls)]
where number_of_balls is the number of balls you want to create.

additional balls can be added to the list:
balls.append(Ball())

now you can access the balls like so:
>>> balls[0]
< __main__.Ball instance at ...>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Object help

2009-01-11 Thread Steven D'Aprano
On Sun, 11 Jan 2009 14:06:22 -0800, killsto wrote:

> I have a class called ball. The members are things like position, size,
> active. So each ball is an object.
> 
> How do I make the object without specifically saying ball1 = ball()?
> Because I don't know how many balls I want; each time it is different.
> 
> The balls are to be thrown in from the outside of the screen. I think
> you get that is enough information.
> 
> This doesn't directly pertain to balls, I have wanted to do something
> like this for many different things but didn't know how.
> 
> I would think something like:
> 
> def newball():
>  x = last_named_ball + 1
> ball_x = ball(size, etc) # this initializes a new ball return ball_x
> 
> But then that would just name a ball ball_x, not ball_1 or ball_2.


This is the TOTALLY wrong approach.

Instead of having named balls, have a list of balls. 

balls = []  # no balls yet
balls.append(Ball())  # one ball comes in from off-screen
balls.append(Ball())  # and a second
del balls[0]  # the first ball got stuck in a tree
balls = []  # all the balls were swept up in a hurricane and lost
balls = [Ball(), Ball(), Ball(), Ball()]  # four balls come in
balls.append(Ball())  # and a fifth
for b in balls:
print b.colour  # print the colour of each ball

and so forth.



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


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

2009-01-11 Thread Carl Banks
On Jan 11, 3:22 pm, "Madhusudan.C.S"  wrote:
>   I am sorry all I am not here to just blame Python. This is just an
> introspection of whether
> what I believe is right. Being a devotee of Python from past 2 years I
> have been writing only
> small apps and singing praises about Python where ever I go. I now got
> a chance to read
> Django's code for some reason. I have now strongly started feeling if
> Python really follows its
> "Readability Counts" philosophy.

Ok, let's clear up a couple misconceptions right now.

First: "Reabability counts" is a design principle of the language, not
a mandate that every Python programmer write readable code.  If Django
project wants to write less readable code, they can.  "Readability
counts" means that Python is designed to make it easy for the Django
project to write readable code if they choose.

Second: "Readability counts" is not the only factor that matters.
There are 19 Zen and sometimes they conflict with each other.  Python
tries to balance all these concerns; it doesn't greedily maximize any
one of them.  Some things might be a little less readable than they
could be, but oftentimes that's because other design considerations
were judged more important in that case.

Having cleared that up, let's consider your specific points.

> For example,
>
>     class A:
>     a = 10
>     b = "Madhu"
>
>     def somemethod(self, arg1):
>         self.c = 20.22
>         d = "some local variable"
>         # do something
>         
>     ...
>     def somemethod2 (self, arg2):
>         self.c = "Changed the variable"
>         # do something 2
>         ...
>
> In such situations, where the Instance variables come into existence
> only when they are used
> it is very difficult to track the flow of code. Its obviously not
> possible to remember what
> instance variable was defined where, when reading some substantial
> amount of code

Impossible?  You are seriously overstating things.

> and where
> it was manipulated for that matter.

This criticism is completely unfair.  Instance variables have to be
manipulated somewhere, and unless your object is immutable, that is
going to happen outside of __init__.  That's true in Java, C++, and
pretty much any other language.

> It becomes so very frustrating
> even when reading a Class's
> code with just 6-8 methods and not more than 100-150 lines of code.
>
> I am interested in knowing if I am reading this kind of code in the
> wrong way mostly because
> of C++/Java hangover since most other languages follow the same
> approach as them?

(Well, it is a lot safer in Python.  In C++, if you try to use an
uninitialized variable, you'd get undefined behavior.  Better to
initialize it to null and at least get a guaranteed segfault.  In
Python if you try to use an uninitialized variable you'd get an
AttributeError.)

> If there
> is a Pythonic way reading this code for better readability? What made
> Python developers to
> adopt this strange strategy keeping "Readibility Counts" in mind?

I'm not going to argue that this doesn't hurt readability, because it
does (though not nearly as much as you claim).  But there are other
considerations, and in this case the flexibility of defining
attributes outside __init__ is worth the potential decrease in
readability.

Here's a couple examples of where it's useful:

1. Sometimes classes are initialized without calling __init__, strange
but true.  Look at the pickle module, for instance.  It creates the
object without calling __init__ then sets all the instance variables
itself.

2. Some classes have factory classmethods that create the object by a
different means than calling __init__.  (In fact, some classes have an
internal method that initializes variables, which __init__ and the
factories both call.)

3. Some objects, such as proxies, have uncertain sets of attributes.
Requiring such objects to predict all the variables they need inside
__init__ would limit their usability.  Programmers would probably
resort to hack-like workarounds like Decorator Design Pattern.

4. It allows a simplification of the object system.  Right now, all
attribute access is handled identically: at any point in time any
attribute may be set.  If you wanted to limit attribute creation to
__init__, then it would mean objects have to have two phases (one,
during __init__, where you can create attributes; the other, where you
can only modify them).  This would add significant complexity, and
"Simple is better than complex.

I'll also point out that even in C++/Java/etc. you have occasions
where an instance variable doesn't do anything until a something
triggers it.  You can look to the constructor to see what it's
initialized to, but it isn't really initialized to anything useful
until some method call sets it to something useful.  (Python makes it
explicit that the variable isn't in use until it is initialized, and
"Explicit is better than implicit".)


In the end, the answer to you question is simply, "Readibilt

Where Find Activestate Python 2.5?

2009-01-11 Thread W. eWatson
I went to their site and the only choice seems 2.6. I looked around and 
found no other choices. Is it possible to get 2.5?

--
   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: Where Find Activestate Python 2.5?

2009-01-11 Thread John Machin
On Jan 12, 9:55 am, "W. eWatson"  wrote:
> I went to their site and the only choice seems 2.6. I looked around and
> found no other choices. Is it possible to get 2.5?

What do you see when you go to 
http://www.activestate.com/activepython/downloads/
and scroll down? I see 3.0, 2.6.1, 2.6, 2.5.2.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-11 Thread Paul Rubin
Carl Banks  writes:
> and where it was manipulated for that matter.
> 
> This criticism is completely unfair.  Instance variables have to be
> manipulated somewhere, and unless your object is immutable, that is
> going to happen outside of __init__.  That's true in Java, C++, and
> pretty much any other language.

The criticism is very valid.  Some languages do support immutable
variables (e.g. "final" declarations in Java, "const" in C++, or
universal immutability in pure functional languages) and they do so
precisely for the purpose of taming the chaos of uncontrolled
mutation.  It would be great if Python also supported immutability.

> I'm not going to argue that this doesn't hurt readability, because it
> does (though not nearly as much as you claim).  But there are other
> considerations, and in this case the flexibility of defining
> attributes outside __init__ is worth the potential decrease in
> readability.

There are cases where this is useful but they're not terribly common.
I think it would be an improvement if creating new object attributes
was by default not allowed outside the __init__ method.  In the cases
where you really do want to create new attributes elsewhere, you'd
have to explicitly enable this at instance creation time, for example
by inheriting from a special superclass:

   class Foo (DynamicAttributes, object): pass

> 4. It allows a simplification of the object system.  Right now, all
> attribute access is handled identically: at any point in time any
> attribute may be set.  If you wanted to limit attribute creation to
> __init__, then it would mean objects have to have two phases (one,
> during __init__, where you can create attributes; the other, where you
> can only modify them).  This would add significant complexity, and
> "Simple is better than complex.

On the other hand, correct is better than buggy.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-11 Thread Carl Banks
On Jan 11, 3:31 pm, Chris Rebert  wrote:
> On Sun, Jan 11, 2009 at 1:22 PM, Madhusudan.C.S  
> wrote:
> >    def somemethod(self, arg1):
> >        self.c = 20.22
> >        d = "some local variable"
> >        # do something
> >        
> >    ...
> >    def somemethod2 (self, arg2):
> >        self.c = "Changed the variable"
> >        # do something 2
> >        ...
>
> > In such situations, where the Instance variables come into existence
> > only when they are used
> > it is very difficult to track the flow of code. Its obviously not
> > possible to remember what
> > instance variable was defined where, when reading some substantial
> > amount of code and where
> > it was manipulated for that matter. It becomes so very frustrating
> > even when reading a Class's
> > code with just 6-8 methods and not more than 100-150 lines of code.
>
> That's bad coding style on the part of the code writer.
> Conditionally-existing instance variables are *evil*.


Do you mean conditionally-useful instance variables evil, or that
conditionally-useful variables are ok but it's evil for them to
conditionally-exist?

The former I don't agree with at all.

If it's the latter, I believe there is something to be said for
variables that exist when they are needed and don't when they're not.
However, I acknowledge that listing all the variables you intend to
use in __init__ is highly comforting, even if it does belie their
current uselessness.


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


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

2009-01-11 Thread Carl Banks
On Jan 11, 5:02 pm, Paul Rubin  wrote:
> Carl Banks  writes:
> > and where it was manipulated for that matter.
>
> > This criticism is completely unfair.  Instance variables have to be
> > manipulated somewhere, and unless your object is immutable, that is
> > going to happen outside of __init__.  That's true in Java, C++, and
> > pretty much any other language.
>
> The criticism is very valid.  Some languages do support immutable
> variables (e.g. "final" declarations in Java, "const" in C++, or
> universal immutability in pure functional languages) and they do so
> precisely for the purpose of taming the chaos of uncontrolled
> mutation.  It would be great if Python also supported immutability.

I don't think what you said (which is fine) makes his criticism valid,
unless you also suggest that all objects should be immutable.

If any objects are mutable, you have to be prepared for objects to
mutated outside the initializer.

I guess it could be a valid criticism of Django's progamming style
("They mutate stuff haphazardly everywhere!!~") but that's not the
Python langauge's problem.


> > 4. It allows a simplification of the object system.  Right now, all
> > attribute access is handled identically: at any point in time any
> > attribute may be set.  If you wanted to limit attribute creation to
> > __init__, then it would mean objects have to have two phases (one,
> > during __init__, where you can create attributes; the other, where you
> > can only modify them).  This would add significant complexity, and
> > "Simple is better than complex.
>
> On the other hand, correct is better than buggy.

What bugginess do you speak of?  Adding a variable outside __init__ is
questionable style, not a bug.  I don't think it's a significant
source of bugs, either.  And I definitely don't think the language
should add a layer of complexity (and I think you're underestimating
the complexity of making the whole object system two-phase) just to
prevent a minor style issue.

pychecker is the appropriate tool to diagnose this issue.


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


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

2009-01-11 Thread Paul Rubin
Carl Banks  writes:
> > The criticism is very valid.  Some languages do support immutable
> > variables (e.g. "final" declarations in Java, "const" in C++, or
> > universal immutability in pure functional languages) and they do so
> > precisely for the purpose of taming the chaos of uncontrolled
> > mutation.  It would be great if Python also supported immutability.
> 
> I don't think what you said (which is fine) makes his criticism valid,
> unless you also suggest that all objects should be immutable.

It would be enough to have a way to make specific objects and instance
attributes immutable.

> If any objects are mutable, you have to be prepared for objects to
> mutated outside the initializer.

Sure, but why have mutable objects all over the place?  And, why
always have attributes visible at all, outside the class definition?
The approach in C++ and Java is to have public and private instance
variables, where the private ones are visible only in the class methods.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-11 Thread Chris Rebert
On Sun, Jan 11, 2009 at 3:15 PM, Carl Banks  wrote:
> On Jan 11, 3:31 pm, Chris Rebert  wrote:
>> On Sun, Jan 11, 2009 at 1:22 PM, Madhusudan.C.S  
>> wrote:
>> >def somemethod(self, arg1):
>> >self.c = 20.22
>> >d = "some local variable"
>> ># do something
>> >
>> >...
>> >def somemethod2 (self, arg2):
>> >self.c = "Changed the variable"
>> ># do something 2
>> >...
>>
>> > In such situations, where the Instance variables come into existence
>> > only when they are used
>> > it is very difficult to track the flow of code. Its obviously not
>> > possible to remember what
>> > instance variable was defined where, when reading some substantial
>> > amount of code and where
>> > it was manipulated for that matter. It becomes so very frustrating
>> > even when reading a Class's
>> > code with just 6-8 methods and not more than 100-150 lines of code.
>>
>> That's bad coding style on the part of the code writer.
>> Conditionally-existing instance variables are *evil*.
>
>
> Do you mean conditionally-useful instance variables evil, or that
> conditionally-useful variables are ok but it's evil for them to
> conditionally-exist?
>
> The former I don't agree with at all.
>
> If it's the latter, I believe there is something to be said for
> variables that exist when they are needed and don't when they're not.
> However, I acknowledge that listing all the variables you intend to
> use in __init__ is highly comforting, even if it does belie their
> current uselessness.

The latter. I never even used the word "useful", so I have no idea
where you got that from.
To reiterate, variables which might only exist under certain
conditions are evil, IMHO.
This is not to say they are not useful in certain specific cases, just
that in general there are better ways to design/structure programs to
avoid them.

Cheers,
Chris

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


Re: Object help

2009-01-11 Thread killsto
On Jan 11, 2:20 pm, Steven D'Aprano  wrote:
> On Sun, 11 Jan 2009 14:06:22 -0800, killsto wrote:
> > I have a class called ball. The members are things like position, size,
> > active. So each ball is an object.
>
> > How do I make the object without specifically saying ball1 = ball()?
> > Because I don't know how many balls I want; each time it is different.
>
> > The balls are to be thrown in from the outside of the screen. I think
> > you get that is enough information.
>
> > This doesn't directly pertain to balls, I have wanted to do something
> > like this for many different things but didn't know how.
>
> > I would think something like:
>
> > def newball():
> >      x = last_named_ball + 1
> >     ball_x = ball(size, etc) # this initializes a new ball return ball_x
>
> > But then that would just name a ball ball_x, not ball_1 or ball_2.
>
> This is the TOTALLY wrong approach.
>
> Instead of having named balls, have a list of balls.
>
> balls = []  # no balls yet
> balls.append(Ball())  # one ball comes in from off-screen
> balls.append(Ball())  # and a second
> del balls[0]  # the first ball got stuck in a tree
> balls = []  # all the balls were swept up in a hurricane and lost
> balls = [Ball(), Ball(), Ball(), Ball()]  # four balls come in
> balls.append(Ball())  # and a fifth
> for b in balls:
>     print b.colour  # print the colour of each ball
>
> and so forth.
>
> --
> Steven

Thanks. That makes sense. It helps a lot. Although, you spelled color
wrong :P.

Just curious, is there another way? How would I do this in c++ which
is listless IIRC.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Object help

2009-01-11 Thread James Mills
On Mon, Jan 12, 2009 at 9:49 AM, killsto  wrote:
> Thanks. That makes sense. It helps a lot. Although, you spelled color
> wrong :P.

color
colour

They are both correct depending on what
country you come from :)

> Just curious, is there another way? How would I do this in c++ which
> is listless IIRC.

Why are you asking us ? We're Python devs/programmers
not C++

cheers
James

PS: I wouldn't touch C++ with a 10-foot pole
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-11 Thread Chris Rebert
On Sun, Jan 11, 2009 at 3:41 PM, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> Carl Banks  writes:

>> If any objects are mutable, you have to be prepared for objects to
>> mutated outside the initializer.
>
> Sure, but why have mutable objects all over the place?  And, why
> always have attributes visible at all, outside the class definition?
> The approach in C++ and Java is to have public and private instance
> variables, where the private ones are visible only in the class methods.

Regarding the second question, Python adheres to the principle that
"We're all consenting adults here" and so does not provide complete
encapsulation like more B&D languages. This is handy sometimes as it
allows one to break through the encapsulation when necessary and
fiddle with the internals. This is not to say that breaking
encapsulation willy-nilly is advised, but it does allow for some neat
hackery every now and again.

Cheers,
Chris

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


Re: Object help

2009-01-11 Thread Chris Rebert
On Sun, Jan 11, 2009 at 3:49 PM, killsto  wrote:
> On Jan 11, 2:20 pm, Steven D'Aprano  cybersource.com.au> wrote:
>> On Sun, 11 Jan 2009 14:06:22 -0800, killsto wrote:
>> > I have a class called ball. The members are things like position, size,
>> > active. So each ball is an object.
>>
>> > How do I make the object without specifically saying ball1 = ball()?
>> > Because I don't know how many balls I want; each time it is different.

>> This is the TOTALLY wrong approach.
>>
>> Instead of having named balls, have a list of balls.

> Just curious, is there another way? How would I do this in c++ which
> is listless IIRC.

If *I* recall correctly, the STL has a `vector` type which is the
equivalent of Python's `list`.

Cheers,
Chris

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


Re: Python 2.6.1 @executable_path

2009-01-11 Thread Michael Torrie
googler.1.webmas...@spamgourmet.com wrote:
> yeap, okay, its just the beginning so I didn't know that the framework
> is still the dylib file.
> Well, I only want to compile python and put the framework in the
> subdirectory. Thats all.
> And the current state is, that the framework is not found because the
> path of the compiled Python
> library is hardcoded so when I move it from /Library/Frameworks/ to my
> app folder it isn't found
> when I start my app.

Okay, that last sentence finally started to make some sense.  Basically
you can fixup your executable and any libraries you need to have the
"@executable_path" part *after* the fact.  This is not about python, but
see this excellent document on bundling Qt apps which explains how this
is done:

http://doc.trolltech.com/4.3/deployment-mac.html

It will tell you every thing you need to know about making it so app
bundles can include and link against libraries and frameworks inside the
app bundle itself.  The keys are "otool" and "install_name_tool."

> 
> I found a ressource that I have to compile it with a dynamic path flag
> like LDFLAGS="-install_name,@executable_path/../Frameworks" to put it
> in the Framework of my app. maybe you know where my problem is. hm.

Yeah that sounds like one way to do it.



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


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

2009-01-11 Thread Mark Wooding
Carl Banks  wrote:

[Dynamically adding and removing instance attributes...]

> Here's a couple examples of where it's useful:
> 
> 1. Sometimes classes are initialized without calling __init__, [...]
> 2. Some classes have factory classmethods [...]
> 3. Some objects, such as proxies, have uncertain sets of attributes. [...]
> 4. It allows a simplification of the object system.  [...]

All good points.  I'd like to add a fifth: it can provide a handy hook
for one module to hang data off of another module's objects.  This sort
of thing isn't very nice, but it's sometimes the best way.

(Other approaches include using wrappers, which might be very invasive
if opaque, or don't actually solve the name-collision problem if
transparent; or maintaining a dictionary, which involves messing about
with weak pointers if you want to keep it from filling with cruft.)

> In the end, the answer to you question is simply, "Readibilty counts,
> but other stuff matters too."

Amen.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-11 Thread Roy Smith
In article 
<34c95e04-5b3f-44bc-a5bf-498518507...@p36g2000prp.googlegroups.com>,
 "Madhusudan.C.S"  wrote:

> In such situations, where the Instance variables come into existence
> only when they are used it is very difficult to track the flow of code.

As the saying goes, "It's possible to write Fortran in any language".

My personal habit is to "declare" all instance variables in the __init__() 
method of every class.  If there's no better value, I set them to None.  
This isn't strictly required, but I think it makes it easier for somebody 
reading the code to understand the class.

I'm not a big fan of dogmatic rules, other than the rule that says you 
should make your code as easy for somebody else to understand as possible.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where Find Activestate Python 2.5?

2009-01-11 Thread W. eWatson

John Machin wrote:

On Jan 12, 9:55 am, "W. eWatson"  wrote:

I went to their site and the only choice seems 2.6. I looked around and
found no other choices. Is it possible to get 2.5?


What do you see when you go to 
http://www.activestate.com/activepython/downloads/
and scroll down? I see 3.0, 2.6.1, 2.6, 2.5.2.
That's correct. If I try to get there (downloads) via starting with the home 
page (click Python tab), select ActivePython in the Community, then I see 
 one large icon button that takes 
me to 2.6. If instead of using the button, I select ActiveState Downloads, 
then I get to . I see ActivePython 
among the Developer Tools. Using that gets me to 
, the big download 2.6 button 
again. Nowhere did I get your url. An interesting maze.


--
   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: Does Python really follow its philosophy of "Readability counts"?

2009-01-11 Thread Carl Banks
On Jan 11, 5:49 pm, Chris Rebert  wrote:
> On Sun, Jan 11, 2009 at 3:15 PM, Carl Banks  wrote:
> > On Jan 11, 3:31 pm, Chris Rebert  wrote:
> >> On Sun, Jan 11, 2009 at 1:22 PM, Madhusudan.C.S  
> >> wrote:
> >> >    def somemethod(self, arg1):
> >> >        self.c = 20.22
> >> >        d = "some local variable"
> >> >        # do something
> >> >        
> >> >    ...
> >> >    def somemethod2 (self, arg2):
> >> >        self.c = "Changed the variable"
> >> >        # do something 2
> >> >        ...
>
> >> > In such situations, where the Instance variables come into existence
> >> > only when they are used
> >> > it is very difficult to track the flow of code. Its obviously not
> >> > possible to remember what
> >> > instance variable was defined where, when reading some substantial
> >> > amount of code and where
> >> > it was manipulated for that matter. It becomes so very frustrating
> >> > even when reading a Class's
> >> > code with just 6-8 methods and not more than 100-150 lines of code.
>
> >> That's bad coding style on the part of the code writer.
> >> Conditionally-existing instance variables are *evil*.
>
> > Do you mean conditionally-useful instance variables evil, or that
> > conditionally-useful variables are ok but it's evil for them to
> > conditionally-exist?
>
> > The former I don't agree with at all.
>
> > If it's the latter, I believe there is something to be said for
> > variables that exist when they are needed and don't when they're not.
> > However, I acknowledge that listing all the variables you intend to
> > use in __init__ is highly comforting, even if it does belie their
> > current uselessness.
>
> The latter. I never even used the word "useful", so I have no idea
> where you got that from.

I was just asking for clarification of your rationale, of which I
imagined two possibilities ("conditional-usefulness is bad", or
"declaring attributes outside of __init__" is bad).  However...


> To reiterate, variables which might only exist under certain
> conditions are evil, IMHO.
> This is not to say they are not useful in certain specific cases, just
> that in general there are better ways to design/structure programs to
> avoid them.

...the way you phrase this suggests to me that conditional-usefulness
*is* what you are really concerned with.  Let me give you an example:

class A:
def __init__(self):
pass
def something(self):
self._conditionally_existent_variable = 1


ISTM that I don't need any restructuring at all to avoid conditional
existence; all I'd have to do is add

self._conditionally_existent_variable = None

to __init__.  If you think I need to restructure this code, than you
evidently care about something more than just conditional existence.
If so, what is it that's so evil about conditionally-existent
variables?  (I'll leave the question open-ended this time.)


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


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

2009-01-11 Thread r
On Jan 11, 6:00 pm, Roy Smith  wrote:
> In article
> <34c95e04-5b3f-44bc-a5bf-498518507...@p36g2000prp.googlegroups.com>,
>
>  "Madhusudan.C.S"  wrote:
> > In such situations, where the Instance variables come into existence
> > only when they are used it is very difficult to track the flow of code.
>
> As the saying goes, "It's possible to write Fortran in any language".
>
> My personal habit is to "declare" all instance variables in the __init__()
> method of every class.  If there's no better value, I set them to None.  
> This isn't strictly required, but I think it makes it easier for somebody
> reading the code to understand the class.
>
> I'm not a big fan of dogmatic rules, other than the rule that says you
> should make your code as easy for somebody else to understand as possible.

Roy i totally agree and as i read down this thread i was thinking i
might get to spit that out first but you beat me -- Darn!

PS: your explanation is also much more eloquent than mine would have
been  :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Object help

2009-01-11 Thread Terry Reedy

killsto wrote:


Just curious, is there another way? How would I do this in c++ which
is listless IIRC.


If you do not have 0) built-in expandable arrays, as in Python, one can

1) program (or find) the equivalent of Python lists;
2) use linked-lists (as long as one does not need O(1) random access);
3) pick a maximum number of items, either for the app or for the run, 
and allocate space for that.


Python enthusiasts include those who see the virtue of option 0).

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


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

2009-01-11 Thread Paul Rubin
Carl Banks  writes:
> If so, what is it that's so evil about conditionally-existent
> variables?  (I'll leave the question open-ended this time.)

I have found they make the code more confusing and bug prone.
It's better to define and document all the instance variables
in one place, in most cases.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-11 Thread Carl Banks
On Jan 11, 5:41 pm, Paul Rubin  wrote:
> Carl Banks  writes:
> > > The criticism is very valid.  Some languages do support immutable
> > > variables (e.g. "final" declarations in Java, "const" in C++, or
> > > universal immutability in pure functional languages) and they do so
> > > precisely for the purpose of taming the chaos of uncontrolled
> > > mutation.  It would be great if Python also supported immutability.
>
> > I don't think what you said (which is fine) makes his criticism valid,
> > unless you also suggest that all objects should be immutable.
>
> It would be enough to have a way to make specific objects and instance
> attributes immutable.

Enough for what, to make the guy's criticism valid?  No it wouldn't.
Or are you just ignoring the OP altogether and complaining about what
bothers you?

For my part I am concerned with answering the OP's issues here, not
yours.


> > If any objects are mutable, you have to be prepared for objects to
> > mutated outside the initializer.
>
> Sure, but why have mutable objects all over the place?  And, why
> always have attributes visible at all, outside the class definition?
> The approach in C++ and Java is to have public and private instance
> variables, where the private ones are visible only in the class methods.

The OP wasn't complaining about the fact that objects aren't
immutable, as far as I can tell, nor about having public and private
variables, so I can't agree Python's lack of these has anything to do
with the OP's concerns.


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


Re: Where Find Activestate Python 2.5?

2009-01-11 Thread Marek Kubica
On Sun, 11 Jan 2009 16:29:16 -0800
"W. eWatson"  wrote:

> Using that gets me to
> , the big download 2.6
> button again. Nowhere did I get your url. An interesting maze.

Tried that "Other Systems and Versions" just below that "Download Now"
button?

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


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

2009-01-11 Thread Carl Banks
On Jan 11, 6:42 pm, Paul Rubin  wrote:
> Carl Banks  writes:
> > If so, what is it that's so evil about conditionally-existent
> > variables?  (I'll leave the question open-ended this time.)
>
> I have found they make the code more confusing and bug prone.
> It's better to define and document all the instance variables
> in one place, in most cases.

That means all I have to do is add a stopgap value in __init__.  I'm
asking Chris why that is evidently not enough, and that I'd have to
structure/design my code to avoid it.


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


Re: Object help

2009-01-11 Thread John Machin
On Jan 12, 10:49 am, killsto  wrote:
> On Jan 11, 2:20 pm, Steven D'Aprano  
> wrote:
> > On Sun, 11 Jan 2009 14:06:22 -0800, killsto wrote:
> > > I have a class called ball. The members are things like position, size,
> > > active. So each ball is an object.
>
> > > How do I make the object without specifically saying ball1 = ball()?
> > > Because I don't know how many balls I want; each time it is different.
>
> > Instead of having named balls, have a list of balls.

Or some other collection or container of objects (e.g. a dict or a
queue), depending on what you are trying to simulate.

> > for b in balls:
> >     print b.colour  # print the colour of each ball
>
> Thanks. That makes sense. It helps a lot. Although, you spelled color
> wrong :P.

At this time of day you are likely to find yourself communicating with
Australians. Get used to it :-)

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


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

2009-01-11 Thread Roy Smith
In article ,
 Chris Rebert  wrote:

> This is not to say that breaking encapsulation willy-nilly is advised, 
> but it does allow for some neat hackery every now and again.

I'm all for neat hackery, except when used in code that I need to read and 
understand.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with -3 switch

2009-01-11 Thread Carl Banks
On Jan 9, 6:11 pm, John Machin  wrote:
> On Jan 10, 6:58 am, Carl Banks  wrote:
>
>
>
> > On Jan 9, 12:36 pm, "J. Cliff Dyer"  wrote:
>
> > > On Fri, 2009-01-09 at 13:13 -0500, Steve Holden wrote:
> > > > Aivar Annamaa wrote:
> > > > >> As was recently pointed out in a nearly identical thread, the -3
> > > > >> switch only points out problems that the 2to3 converter tool can't
> > > > >> automatically fix. Changing print to print() on the other hand is
> > > > >> easily fixed by 2to3.
>
> > > > >> Cheers,
> > > > >> Chris
>
> > > > > I see.
> > > > > So i gotta keep my own discipline with print() then :)
>
> > > > Only if you don't want to run your 2.x code through 2to3 before you use
> > > > it as Python 3.x code.
>
> > > > regards
> > > >  Steve
>
> > > And mind you, if you follow that route, you are programming in a
> > > mightily crippled language.
>
> > How do you figure?
>
> > I expect that it'd be a PITA in some cases to use the transitional
> > dialect (like getting all your Us in place), but that doesn't mean the
> > language is crippled.
>
> What is this "transitional dialect"? What does "getting all your Us in
> place" mean?

Transitional dialect is the subset of Python 2.6 that can be
translated to Python3 with 2to3 tool.  Getting all your Us in place
refers to prepending a u to strings to make them unicode objects,
which is something 2to3 users are highly advised to do to keep hassles
to a minimum.  (Getting Bs in place would be a good idea too.)


> Steve & Cliff are talking about the rather small subset of Python that
> is not only valid syntax in both 2.x and 3.x but also has the same
> meaning in 2.x and 3.x.

That would be a crippled language, yes.  But I do not believe that's
what Steve and Cliff are referring to.  Steve wrote of "running your
code through 2to3", and that was what Cliff followed up to, so I
believe they are both referring to writing valid code in 2.6 which is
able to be translated through 2to3, and then generating 3.0 code using
2to3.  That is not a crippled language at all, just a PITA sometimes.


> > > It's about as bad as trying to write
> > > cross-browser CSS.  Don't put yourself through that pain if you don't
> > > have to.
>
> > Have you tried doing that, or are you imagining how it will be?  I'm
> > curious about people's actual experiences.
>
> I maintain two packages, xlrd which supports 2.1 to 2.6, and xlwt
> which supports 2.3 to 2.6. I've done suck-it-and-see trials on being
> able to support 3.x as well from the same codebase, and it's turned
> out reasonably well. xlrd already had a module called timemachine
> which caters for version- dependent stuff. Extending this to 3.x was
> more a voyage of discovery than a PITA. timemachine.py is "crippled"
> in Cliff's sense, in that because I'm the principal user I need to
> make it robust and idiot-proof, so it has been written under the
> following constraints:
> (1) not one copy of timemachine.py for 2.1, one for 2.2, one for
> 2.3, ... etc; just one copy, period.
> (2) means that it must use syntax that's valid in all supported
> versions
> (3) must be able to be processed by 2to3 without causing a commotion
> (4) the original version and the 2to3 output must have the same effect
> when imported by 3.x.
>
> So one ends up with code like:
>    glued = BYTES_NULL.join(list_of_pieces_of_a_binary_file)
> which is supported by timemachine definitions like
> BYTES_NULL = bytes(0) # 3.x ... note b'' is not valid in 2.x
> BYTES_NULL = '' # 2.x
>
> BYTES_NULL.join() may be ugly, but it's not crippled, it's fully
> functional, and it would be very easy to find and change in the future
> in two possible scenarios (1) drop 2.x support (2) change codebase to
> be mostly 3.x, support 2.x by a (mythical, hoped-for) 3to2 mechanism.

Cool, thanks.


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


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

2009-01-11 Thread Chris Rebert
On Sun, Jan 11, 2009 at 4:33 PM, Carl Banks  wrote:
> On Jan 11, 5:49 pm, Chris Rebert  wrote:
>> On Sun, Jan 11, 2009 at 3:15 PM, Carl Banks  wrote:
>> > On Jan 11, 3:31 pm, Chris Rebert  wrote:
>> >> On Sun, Jan 11, 2009 at 1:22 PM, Madhusudan.C.S  
>> >> wrote:
>> >> >def somemethod(self, arg1):
>> >> >self.c = 20.22
>> >> >d = "some local variable"
>> >> ># do something
>> >> >
>> >> >...
>> >> >def somemethod2 (self, arg2):
>> >> >self.c = "Changed the variable"
>> >> ># do something 2
>> >> >...
>>
>> >> > In such situations, where the Instance variables come into existence
>> >> > only when they are used
>> >> > it is very difficult to track the flow of code. Its obviously not
>> >> > possible to remember what
>> >> > instance variable was defined where, when reading some substantial
>> >> > amount of code and where
>> >> > it was manipulated for that matter. It becomes so very frustrating
>> >> > even when reading a Class's
>> >> > code with just 6-8 methods and not more than 100-150 lines of code.
>>
>> >> That's bad coding style on the part of the code writer.
>> >> Conditionally-existing instance variables are *evil*.
>>
>> > Do you mean conditionally-useful instance variables evil, or that
>> > conditionally-useful variables are ok but it's evil for them to
>> > conditionally-exist?
>>
>> > The former I don't agree with at all.
>>
>> > If it's the latter, I believe there is something to be said for
>> > variables that exist when they are needed and don't when they're not.
>> > However, I acknowledge that listing all the variables you intend to
>> > use in __init__ is highly comforting, even if it does belie their
>> > current uselessness.
>>
>> The latter. I never even used the word "useful", so I have no idea
>> where you got that from.
>
> I was just asking for clarification of your rationale, of which I
> imagined two possibilities ("conditional-usefulness is bad", or
> "declaring attributes outside of __init__" is bad).  However...
>
>
>> To reiterate, variables which might only exist under certain
>> conditions are evil, IMHO.
>> This is not to say they are not useful in certain specific cases, just
>> that in general there are better ways to design/structure programs to
>> avoid them.
>
> ...the way you phrase this suggests to me that conditional-usefulness
> *is* what you are really concerned with.  Let me give you an example:
>
> class A:
>def __init__(self):
>pass
>def something(self):
>self._conditionally_existent_variable = 1
>
>
> ISTM that I don't need any restructuring at all to avoid conditional
> existence; all I'd have to do is add
>
> self._conditionally_existent_variable = None
>
> to __init__.  If you think I need to restructure this code, than you
> evidently care about something more than just conditional existence.

No, this is exactly the sort of restructuring I was referring to; and
nothing more. Making that one-line change would be sufficient for me.
Perhaps "restructuring" was a poor choice of words...

Cheers,
Chris

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


urllib2 - 403 that _should_ not occur.

2009-01-11 Thread James Mills
Hey all,

The following fails for me:

>>> from urllib2 import urlopen
>>> f = 
>>> urlopen("http://groups.google.com/group/chromium-announce/feed/rss_v2_0_msgs.xml";)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.6/urllib2.py", line 124, in urlopen
return _opener.open(url, data, timeout)
  File "/usr/lib/python2.6/urllib2.py", line 389, in open
response = meth(req, response)
  File "/usr/lib/python2.6/urllib2.py", line 502, in http_response
'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.6/urllib2.py", line 427, in error
return self._call_chain(*args)
  File "/usr/lib/python2.6/urllib2.py", line 361, in _call_chain
result = func(*args)
  File "/usr/lib/python2.6/urllib2.py", line 510, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
>>>

However, that _same_ url works perfectly fine on the
same machine (and same network) using any of:
 * curl
 * wget
 * elinks
 * firefox

Any helpful ideas ?

cheers
James

--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


File layout in development stage

2009-01-11 Thread Steven Woody
Hi,

Adapted your kindly suggestions in a previous post,  I now decide to
organize my source tree in a pattern like below:


prj:
src:
lib:
foomodule.py
barmodule.py
scripts:
prj_main.py
 test:
 footest.py
 bartest.py
 ...


That is, I want to put the top-level scripts in  prj/src/scripts  and
share libraries in prj/src/lib.  In the prj/test directory I want to
put my unit-tests using unittest module.  My question is that when in
development stage there is  no file is actually distributed, so how
should a python source in one directory refer to (import) another
module in another directory?

Thanks in advance.

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


Re: File layout in development stage

2009-01-11 Thread alex goretoy
sys.path.append()

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Mon, Jan 12, 2009 at 2:00 AM, Steven Woody  wrote:

> Hi,
>
> Adapted your kindly suggestions in a previous post,  I now decide to
> organize my source tree in a pattern like below:
>
>
> prj:
>src:
>lib:
>foomodule.py
>barmodule.py
>scripts:
>prj_main.py
> test:
> footest.py
> bartest.py
> ...
>
>
> That is, I want to put the top-level scripts in  prj/src/scripts  and
> share libraries in prj/src/lib.  In the prj/test directory I want to
> put my unit-tests using unittest module.  My question is that when in
> development stage there is  no file is actually distributed, so how
> should a python source in one directory refer to (import) another
> module in another directory?
>
> Thanks in advance.
>
> -
> narke
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 - 403 that _should_ not occur.

2009-01-11 Thread Philip Semanchuk


On Jan 11, 2009, at 8:59 PM, James Mills wrote:


Hey all,

The following fails for me:


from urllib2 import urlopen
f = urlopen("http://groups.google.com/group/chromium-announce/feed/rss_v2_0_msgs.xml 
")

Traceback (most recent call last):
 File "", line 1, in 
 File "/usr/lib/python2.6/urllib2.py", line 124, in urlopen
   return _opener.open(url, data, timeout)
 File "/usr/lib/python2.6/urllib2.py", line 389, in open
   response = meth(req, response)
 File "/usr/lib/python2.6/urllib2.py", line 502, in http_response
   'http', request, response, code, msg, hdrs)
 File "/usr/lib/python2.6/urllib2.py", line 427, in error
   return self._call_chain(*args)
 File "/usr/lib/python2.6/urllib2.py", line 361, in _call_chain
   result = func(*args)
 File "/usr/lib/python2.6/urllib2.py", line 510, in http_error_default
   raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden




However, that _same_ url works perfectly fine on the
same machine (and same network) using any of:
* curl
* wget
* elinks
* firefox

Any helpful ideas ?


The remote server doesn't like your user agent?

It'd be easier to help if you post a working sample.

Cheers
Philip


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


ActiveState Python Together with "Regular" Python) ((DLE)

2009-01-11 Thread W. eWatson
I installed "Python" 2.5 a few months ago with IDLE, and decided I'd like to 
try windowpy from ActiveState. Is having both of these installed going to 
cause me trouble?

--
   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: urllib2 - 403 that _should_ not occur.

2009-01-11 Thread James Mills
On Mon, Jan 12, 2009 at 12:58 PM, Philip Semanchuk  wrote:
>
> On Jan 11, 2009, at 8:59 PM, James Mills wrote:
>
>> Hey all,
>>
>> The following fails for me:
>>
> from urllib2 import urlopen
> f =
> urlopen("http://groups.google.com/group/chromium-announce/feed/rss_v2_0_msgs.xml";)
>>
>> Traceback (most recent call last):
>>  File "", line 1, in 
>>  File "/usr/lib/python2.6/urllib2.py", line 124, in urlopen
>>   return _opener.open(url, data, timeout)
>>  File "/usr/lib/python2.6/urllib2.py", line 389, in open
>>   response = meth(req, response)
>>  File "/usr/lib/python2.6/urllib2.py", line 502, in http_response
>>   'http', request, response, code, msg, hdrs)
>>  File "/usr/lib/python2.6/urllib2.py", line 427, in error
>>   return self._call_chain(*args)
>>  File "/usr/lib/python2.6/urllib2.py", line 361, in _call_chain
>>   result = func(*args)
>>  File "/usr/lib/python2.6/urllib2.py", line 510, in http_error_default
>>   raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
>> urllib2.HTTPError: HTTP Error 403: Forbidden
>
>>
>> However, that _same_ url works perfectly fine on the
>> same machine (and same network) using any of:
>> * curl
>> * wget
>> * elinks
>> * firefox
>>
>> Any helpful ideas ?
>
> The remote server doesn't like your user agent?
>
> It'd be easier to help if you post a working sample.

That was a working sample! The "User-Agent" didn't
occur to me :) Thanks - I think that might be it.

Why Google would deny access to services by
unknown User Agents is beyond me - especially
since in most cases User Agents strings are not
strict.

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


Re: urllib2 - 403 that _should_ not occur.

2009-01-11 Thread Philip Semanchuk


On Jan 11, 2009, at 10:05 PM, James Mills wrote:

On Mon, Jan 12, 2009 at 12:58 PM, Philip Semanchuk > wrote:


On Jan 11, 2009, at 8:59 PM, James Mills wrote:


Hey all,

The following fails for me:


from urllib2 import urlopen
f =
urlopen("http://groups.google.com/group/chromium-announce/feed/rss_v2_0_msgs.xml 
")


Traceback (most recent call last):
File "", line 1, in 
File "/usr/lib/python2.6/urllib2.py", line 124, in urlopen
 return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 389, in open
 response = meth(req, response)
File "/usr/lib/python2.6/urllib2.py", line 502, in http_response
 'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.6/urllib2.py", line 427, in error
 return self._call_chain(*args)
File "/usr/lib/python2.6/urllib2.py", line 361, in _call_chain
 result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 510, in  
http_error_default

 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden




However, that _same_ url works perfectly fine on the
same machine (and same network) using any of:
* curl
* wget
* elinks
* firefox

Any helpful ideas ?


The remote server doesn't like your user agent?

It'd be easier to help if you post a working sample.


That was a working sample!


Oooops, I guess it is my brain that's not working, then! Sorry about  
that.


I tried your sample and got the 403. This works for me:

>>> import urllib2
>>> user_agent="Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0)  
Gecko/25250101"
>>> url="http://groups.google.com/group/chromium-announce/feed/rss_v2_0_msgs.xml 
"

>>> req = urllib2.Request(url, None, { 'User-Agent' : user_agent})
>>> f = urllib2.urlopen(req)
>>> s=f.read()
>>> f.close()
>>> print s


  
  Chromium-Announce Google Group
  http://groups.google.com/group/chromium-announce
  This list is intended for important product  
announcements that affect the majority of

etc.



Why Google would deny access to services by
unknown User Agents is beyond me - especially
since in most cases User Agents strings are not
strict.


Some sites ban UAs that look like bots. I know there's a Java-based  
bot with a distinct UA that was really badly-behaved when visiting my  
server. Ignored robots.txt, fetched pages as quickly as it could etc.  
That was worthy of banning. FWIW, when I try the code above with a UA  
of "funny fish" it still works OK, so it looks like the  
groups.google.com server has it out for UAs with Python in them, not  
just unknown ones.


I'm sure that if you changed wget's UA string to something Pythonic it  
would start to fail too.



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


Re: sys.stdout.write()'s bug or doc bug?

2009-01-11 Thread Aahz
In article ,
Qiangning Hong   wrote:
>
>So, my question is, as sys.stdout IS a file object, why it does not
>use its encoding attribute to convert the given unicode?  An
>implementation bug? A documenation bug?

Please file a bug on bugs.python.org -- that's the only way this can be
tracked.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

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


Re: urllib2 - 403 that _should_ not occur.

2009-01-11 Thread James Mills
On Mon, Jan 12, 2009 at 1:25 PM, Philip Semanchuk  wrote:
> Oooops, I guess it is my brain that's not working, then! Sorry about that.

Nps.

> I tried your sample and got the 403. This works for me:

(...)

> Some sites ban UAs that look like bots. I know there's a Java-based bot with
> a distinct UA that was really badly-behaved when visiting my server. Ignored
> robots.txt, fetched pages as quickly as it could etc. That was worthy of
> banning. FWIW, when I try the code above with a UA of "funny fish" it still
> works OK, so it looks like the groups.google.com server has it out for UAs
> with Python in them, not just unknown ones.
>
> I'm sure that if you changed wget's UA string to something Pythonic it would
> start to fail too.

My problem that I'm solving and my use-case
is  a tool to periodically check configured RSS
feeds for updates. I was going to use urllib2
to get the data and pass this off to feedparser.parse(...)

Because of the UA problem though (which can
be overcome) - I decided to try a different approach
and use feedparse entirely (which uses urllib internally).

Problem is, feedparser doesn't store the http's
response content anywhere - only the parsed
results - *sigh*.

My solution now is to parse and store the data
I required in a simple object and pickle this to a
set of cached files and compare this against
hashed versions of the content.

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


Re: Is negative seek() from EOF of a GzipFile supported on Python 2.5.2 ?

2009-01-11 Thread Gabriel Genellina

En Sun, 11 Jan 2009 08:12:27 -0200, Barak, Ron 
escribió:


I googled a bit, and found http://bugs.python.org/issue1355023.
It seems that this patch implemented fuller seek() for GzipFile around  
November 2006 (including whence==2).
Do I misunderstand and this patch was not actually implemented, namely,  
is seek(-n,2) not implemented in Python 2.5.2 ?


The source of gzip.py on my system seems to suggest that negative seeks  
are supported:


The source comments are misleading: "negative seeks" means seeking
backwards (towards the beginning of the file), not offset<0.
The second argument to seek (whence) was added in 2.6, and only accepts 0
or 1; whence==2 isn't supported.

--
Gabriel Genellina

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


Re: Object help

2009-01-11 Thread killsto
>
> > Thanks. That makes sense. It helps a lot. Although, you spelled color
> > wrong :P.
>
> At this time of day you are likely to find yourself communicating with
> Australians. Get used to it :-)
>
> Cheers,
> John

I was kidding. IMO, we Americans should spell color like everyone
else. Heck, use the metric system too while we are at it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Object help

2009-01-11 Thread James Mills
On Mon, Jan 12, 2009 at 2:26 PM, killsto  wrote:
> I was kidding. IMO, we Americans should spell color like everyone
> else. Heck, use the metric system too while we are at it.

Yes well why don't you start up a rally and convince
your brand new shiny government to catch up with
the rest of the world! :)

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


Re: Problem with -3 switch

2009-01-11 Thread John Machin
On Jan 12, 12:23 pm, Carl Banks  wrote:
> On Jan 9, 6:11 pm, John Machin  wrote:
>
>
>
>
>
> > On Jan 10, 6:58 am, Carl Banks  wrote:
>
> > > On Jan 9, 12:36 pm, "J. Cliff Dyer"  wrote:
>
> > > > On Fri, 2009-01-09 at 13:13 -0500, Steve Holden wrote:
> > > > > Aivar Annamaa wrote:
> > > > > >> As was recently pointed out in a nearly identical thread, the -3
> > > > > >> switch only points out problems that the 2to3 converter tool can't
> > > > > >> automatically fix. Changing print to print() on the other hand is
> > > > > >> easily fixed by 2to3.
>
> > > > > >> Cheers,
> > > > > >> Chris
>
> > > > > > I see.
> > > > > > So i gotta keep my own discipline with print() then :)
>
> > > > > Only if you don't want to run your 2.x code through 2to3 before you 
> > > > > use
> > > > > it as Python 3.x code.
>
> > > > > regards
> > > > >  Steve
>
> > > > And mind you, if you follow that route, you are programming in a
> > > > mightily crippled language.
>
> > > How do you figure?
>
> > > I expect that it'd be a PITA in some cases to use the transitional
> > > dialect (like getting all your Us in place), but that doesn't mean the
> > > language is crippled.
>
> > What is this "transitional dialect"? What does "getting all your Us in
> > place" mean?
>
> Transitional dialect is the subset of Python 2.6 that can be
> translated to Python3 with 2to3 tool.

I'd never seen it called "transitional dialect" before.

>  Getting all your Us in place
> refers to prepending a u to strings to make them unicode objects,
> which is something 2to3 users are highly advised to do to keep hassles
> to a minimum.  (Getting Bs in place would be a good idea too.)

Ummm ... I'm not understanding something. 2to3 changes u"foo" to
"foo", doesn't it? What's the point of going through the code and
changing all non-binary "foo" to u"foo" only so that 2to3 can rip the
u off again? What hassles? Who's doing the highly-advising where and
with what supporting argument?

"Getting Bs into place" is necessary eventually. Whether it is
worthwhile trying to find these in advance, or waiting for them to be
picked up at testing time is a bit of a toss-up.

Let's look at this hypothetical but fairly realistic piece of 2.x
code:
OLE2_SIGNATURE = "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
def is_ole2_file(filepath):
 return open(filepath, "rb").read(8) == OLE2_SIGNATURE

This is already syntactically valid 3.x code, and won't be changed by
2to3, but it won't work in 3.x because b"x" != "x" for all x. In this
case, the cause of test failures should be readily apparent; in other
cases the unexpected exception or test failure may happen at some
distance.

The 3.x version needs to have the effect of:
OLE2_SIGNATURE = b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
def is_ole2_file(filepath):
 return open(filepath, "rb").read(8) == OLE2_SIGNATURE

So in my regional variation of the transitional dialect, this becomes:
from timemachine import *
OLE2_SIGNATURE = BYTES_LITERAL("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1")
def is_ole2_file(filepath):
 return open(filepath, "rb").read(8) == OLE2_SIGNATURE
# NOTE: don't change "rb"
...
and timemachine.py contains (amongst other things):
import sys
python_version = sys.version_info[:2] # e.g. version 2.4 -> (2, 4)
if python_version >= (3, 0):
BYTES_LITERAL = lambda x: x.encode('latin1')
else:
BYTES_LITERAL = lambda x: x

It is probably worthwhile taking an up-front inventory of all file open
() calls and [c]StringIO.StringIO() calls -- is the file being used as
a text file or a binary file?
If a text file, check that any default encoding is appropriate.
If a binary file, ensure there's a "b" in the mode (real file) or you
supply (in 3.X) an io.BytesIO() instance, not an io.StringIO()
instance.

>
> > Steve & Cliff are talking about the rather small subset of Python that
> > is not only valid syntax in both 2.x and 3.x but also has the same
> > meaning in 2.x and 3.x.
>
> That would be a crippled language, yes.  But I do not believe that's
> what Steve and Cliff are referring to.  Steve wrote of "running your
> code through 2to3", and that was what Cliff followed up to, so I
> believe they are both referring to writing valid code in 2.6 which is
> able to be translated through 2to3, and then generating 3.0 code using
> 2to3.  That is not a crippled language at all, just a PITA sometimes.

Uh huh; I assumed that "crippled" was being applied to the worse of
the two options :-)

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


Re: urllib2 - 403 that _should_ not occur.

2009-01-11 Thread Chris Mellon
On Sun, Jan 11, 2009 at 9:05 PM, James Mills
 wrote:
> On Mon, Jan 12, 2009 at 12:58 PM, Philip Semanchuk  
> wrote:
>>
>> On Jan 11, 2009, at 8:59 PM, James Mills wrote:
>>
>>> Hey all,
>>>
>>> The following fails for me:
>>>
>> from urllib2 import urlopen
>> f =
>> urlopen("http://groups.google.com/group/chromium-announce/feed/rss_v2_0_msgs.xml";)
>>>
>>> Traceback (most recent call last):
>>>  File "", line 1, in 
>>>  File "/usr/lib/python2.6/urllib2.py", line 124, in urlopen
>>>   return _opener.open(url, data, timeout)
>>>  File "/usr/lib/python2.6/urllib2.py", line 389, in open
>>>   response = meth(req, response)
>>>  File "/usr/lib/python2.6/urllib2.py", line 502, in http_response
>>>   'http', request, response, code, msg, hdrs)
>>>  File "/usr/lib/python2.6/urllib2.py", line 427, in error
>>>   return self._call_chain(*args)
>>>  File "/usr/lib/python2.6/urllib2.py", line 361, in _call_chain
>>>   result = func(*args)
>>>  File "/usr/lib/python2.6/urllib2.py", line 510, in http_error_default
>>>   raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
>>> urllib2.HTTPError: HTTP Error 403: Forbidden
>>
>>>
>>> However, that _same_ url works perfectly fine on the
>>> same machine (and same network) using any of:
>>> * curl
>>> * wget
>>> * elinks
>>> * firefox
>>>
>>> Any helpful ideas ?
>>
>> The remote server doesn't like your user agent?
>>
>> It'd be easier to help if you post a working sample.
>
> That was a working sample! The "User-Agent" didn't
> occur to me :) Thanks - I think that might be it.
>
> Why Google would deny access to services by
> unknown User Agents is beyond me - especially
> since in most cases User Agents strings are not
> strict.

If you look at the actual response text and not just the error code,
you will get a clear explanation of why you were forbidden.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ActiveState Python Together with "Regular" Python) ((DLE)

2009-01-11 Thread John Machin
On Jan 12, 2:00 pm, "W. eWatson"  wrote:
> I installed "Python" 2.5 a few months ago with IDLE, and decided I'd like to
> try windowpy from ActiveState. Is having both of these installed going to
> cause me trouble?

What is "windowpy from ActiveState"? If you mean you wanted to try the
PythonWin IDE instead of IDLE, all you needed to do was go to
http://sourceforge.net/projects/pywin32/ hit the big download button
and make sure you get the 2.5 version (it's the default atm) and
install it.

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


Re: template inheritance

2009-01-11 Thread James Matthews
Not always sometimes you want to show some template code (You have a blog
about web dev) and sometimes you want to nest some code.

On Sun, Jan 11, 2009 at 10:04 PM, Diez B. Roggisch wrote:

> Alex K schrieb:
>
>> While building a website using template inheritance one usually does
>> the following:
>>
>> fetch from database
>> fetch from some more data from database
>> ... << more required computations
>> then at the end render the template with the fetched data
>>
>> Without template inheritance one usually does the following:
>>
>> fetch from database
>> render this part of the site with this fetched data
>> fetch some more data from the database
>> render this other part of the site with the fetched data
>> ...
>> etc
>>
>> The first approach is much more elegant and leads to easier to
>> maintain code. However the user will have to wait till the end of the
>> fetching (long computations) before any rendering can take place. In
>> the second approach however the site loads as we are fetching the data
>> which is more convenient to the user.
>>
>> Am I correct to assume this? Is there a way to get the best of both
>> worlds? Thank you.
>>
>
> I don't think that the question of inheritance or not is really relevant
> here.
>
> It's a matter of how the templating system is written - does it collect all
> the data beforehand, or not, is it potentially using e.g. generators and so
> forth.
>
> And of course how the programmer uses the templating system. does he fetch
> all the data beforehand, or does he use lazy generation approachs - again,
> e.g. generators, or callbacks.
>
> Besides, *usually* the 20-39Kb of a website itself aren't the problem I'd
> say - loading referenced resources is much more of an issue.
>
> And AFAIK the render-mode matters, too. If the site is XHTML-compliant, the
> browser can start the rendering once the HTML is complete - otherwise, it
> might wait until the referenced resources are all loaded to calculate the
> layout.
>
> Diez
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.astorandblack.com/
--
http://mail.python.org/mailman/listinfo/python-list


hlep: a text search and rename question

2009-01-11 Thread sensen
matter description:

when a use an tools to do the ape to flac convert, i can use the cue
file attached with ape, but the problem is the converted flac file
don't name by the title in the cue file but like Track_1.flac,
Track_2.flac ... , so i want to write a script to do this work, system
is xp sp2, the python is 2.44, i have a plone site in this computer,
that is why i want to use python to do this work.

so simplify and example

CDImage.cue, Track_1.flac, Track_2.flac, Track_3.flac, Track_4.flac
all above files in the same folder.

the cue file is just a text file like bellow:


PERFORMER "Dido"
TITLE "Life For Rent"
FILE "Dido - Life for Rent.ape" WAVE
  TRACK 01 AUDIO
TITLE "White Flag"
PERFORMER "Dido"
INDEX 01 00:00:00
  TRACK 02 AUDIO
TITLE "Stoned"
PERFORMER "Dido"
INDEX 00 04:00:03
INDEX 01 04:01:45
  TRACK 03 AUDIO
TITLE "Life For Rent"
PERFORMER "Dido"
INDEX 00 09:56:47
INDEX 01 09:56:53
  TRACK 04 AUDIO
TITLE "Mary's In India"
PERFORMER "Dido"
INDEX 01 13:37:57

the things i want to do

1. search the current folder cue file (only one cue file) contents.
find the TITLE "White Flag" and get the White Flag and maybe we
can save it to a var.
2. then rename the Track_1.flac to the White Flag.flac
3. search the next title TITLE "Stoned" and save ti to var.
4. then rename the Track_2.flac to the Stoned.flac.
5. do the same things to the end title.

someone can give some outline, or code is more wonderful.  thanks in
advance.
--
http://mail.python.org/mailman/listinfo/python-list