Re: Regular expression that skips single line comments?

2009-01-19 Thread martinjamesevans

Firstly, a huge thanks to all for the solutions!  Just what I was
looking for.



> (Aside: why are you doing a case-insensitive match for a non-letter? Are
> there different upper- and lower-case dollar signs?)

As you can probably imagine, I had simplified the problem slightly,
the language uses a couple of different introducers and also uses both
numbers and letters (but only single characters).

I was going to go with a similar idea of parsing per line but was
trying to give RE another chance. I've used RE often in the past but
for some reason this one had got under my skin.

I found this to be quite an interesting little tool:
http://www.gskinner.com/RegExr/

Martin

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


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

2009-01-19 Thread Paul Rubin
"Tim Rowe"  writes:
> I was actually at the European Space Agency's Toulouse site the week
> after the Ariane 5 incident. I've been at jollier funerals. I can't
> help thinking that thinking that the team would have benefited from
> reading David Parnas's work on the specification of the A-7E avionics.

Thanks, these articles look interesting, though there is a lot to read:

  http://www.chacs.itd.nrl.navy.mil/publications/scr-a7e/index.html

Was there something else you were referring to?
--
http://mail.python.org/mailman/listinfo/python-list


Re: reading file to list

2009-01-19 Thread alex23
On Jan 20, 1:39 pm, Xah Lee  wrote:
> consider code produced by corporations, as opposed to with respect to
> some academic or philsophical logical analysis. Looked in another way,
> consider if we can compile stat of all existing pyhton code used in
> real world, you'll find the above style is rarely used.

I've worked for several corporations that used Python and at -all- of
them the developers were not only aware of list comprehensions, they
used them regularly. Same with iterators. Not -one- of them found them
to be "computer sciency OOP jargons" but useful metaphors that made
their code more concise without sacrificing readability.

Not everything new is crap, y'know. Neither is everything that you
fail to understand the first time you're exposed to it.

I find it kinda funny that you constantly criticise "academic"
language development when it seems pretty clear from your posts that
you've never actually engaged in any practical application-focused
development in your life. But as they say: those that can do, those
that can't post godawful screeds to their much-hyped-on-usenet vanity
blogs...
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Paul Rubin
"Tim Rowe"  writes:
> Unless it's changed since I used it, technically, SPADE doesn't allow
> or disallow anything. 

Right, it's an external tool, like pylint; you can still compile code
that SPADE complains about.  Sorry if I wan't more clear.  I just
meant SPADE would flag the code.

> Since the value appears to come from a sensor, the only way one
> could prove that there would be no overflow would be to state it as
> a part of the specification of what is read in. If that
> specification doesn't match the specification of the actual sensor,
> that's nothing to do with the programming language or, for that
> matter, the program itself.  It's a specification mismatch.

Right, that's the point, the assumption about the sensor reading being
in a certain range would have to stated in the specification rather
than implicit in the code; and as such, the problem would more likely
to have been caught at the systems engineering level.

> I was actually at the European Space Agency's Toulouse site the week
> after the Ariane 5 incident. I've been at jollier funerals. I can't
> help thinking that thinking that the team would have benefited from
> reading David Parnas's work on the specification of the A-7E avionics.

Later there was a static analysis of the Ariane code by Cousot et al,
that flagged the error.  I haven't yet looked up the paper to see
exactly what it found.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Russ P.
On Jan 19, 10:33 pm, Luis Zarrabeitia  wrote:

> So, Arianne 5's problem had nothing to do with _enforced data hiding_. (Why do
> you keep calling it 'encapsulation'?).

I keep calling it encapsulation because that is a widely accepted,
albeit not universal, definition of encapsulation. Google
"encapsulation" and see for yourself. For example, here is what the
Wikipedia page on OOP says:

Encapsulation conceals the functional details of a class from objects
that send messages to it.

Here is what another webpage says:

Definition: In Object Oriented Programming, encapsulation is an
attribute of object design. It means that all of the object's data is
contained and hidden in the object and access to it restricted to
members of that class.

Because those definitions are not universally accepted, however, I
usually say "enforced encapsulation" or "data hiding" to mean what
"encapsulation" means to most OO programmers who use a language other
than Python.

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


Re: what's the point of rpython?

2009-01-19 Thread Kay Schluehr
On 17 Jan., 01:37, "Brendan Miller"  wrote:

> Is this going anywhere or is this just architecture astronautics?
>
> The RPython project seems kind of interseting to me and I'd like to
> see more python implementations, but looking at the project I can't
> help but think that they haven't really explained *why* they are doing
> the things they are doing.

Remember that the original objective of PyPy was to improve the JIT.
Psyco is limited by the fact that the whole runtime is implemented in
C. The infamous "faster than C" actually refers to work on program
specializers on C code i.e. treating C as a language that is JIT
compiled on a fine grained level ( block structure - whole function
JIT compilation wouldn't obviously yield any advantages ).

So it is not just the application level Python code that shall run
through the JIT but also the interpreter level code. So why not equate
them and think about interpreter level code as Python as well? This
might be the idea. But then the problem of bootstrapping comes up:
there is no interpreter level code with the required properties. Hence
RPython that can serve as a foundation.

I'm also not sure I like the approach. Rather than designing a whole
new runtime for having a fully reflective system I'd model C in Python
( call it CiPy ) and create a bijection between CiPy code and C code.
Once this has been established one can study other translations of
CiPy or Python into CiPy ( not unlike Pyrex/Cython ) doing systematic
refactorings on CiPy code in Python, study properties using runtime
reflection, experiment with macro systems etc. All of this is done in
PyPy as well but sometimes it seems the team has created more new
problems than they solved.

> Anyway, I can tell this is the sort of question that some people will
> interpret as rude. Asking hard questions is never polite, but it is
> always necessary :)

I think it is a good question.
--
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting documentation

2009-01-19 Thread Alan G Isaac

On 1/19/2009 5:03 PM Terry Reedy apparently wrote:

I have not seen 3.0 emit a % deprecation warning.



Point taken.

But the vocabulary of PEP 4 suggests that
"obsolete" and "deprecated" are synonyms,
and PEP 4 lists obsolete modules without
deprecation warnings.

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


Re: ifconfig in python

2009-01-19 Thread alex goretoy
ifconfig -a|grep "inet addr"|awk '{print $2}'

wget http://myip.dk&&; cat index.html|grep "http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Tue, Jan 20, 2009 at 3:42 AM, Дамјан Георгиевски wrote:

> Something *like*  this could work:
>
>myip = 
> urllib2.urlopen('http://whatismyip.org/').read(
> )
>
> of course then you are depending on an external service, not a very
> reliable one even. But then again, you might create an internal service
> like that yourself.
>
> This cgi-bin shell code like this for ex:
>
> #! /bin/sh
> echo "Content-type: text/plain"
> echo
> echo "${REMOTE_ADDR}"
>
>
> --
> дамјан ( http://softver.org.mk/damjan/ )
>
> Spammers scratch here with a diamond to find my address:
> |||
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting documentation

2009-01-19 Thread Alan G Isaac

On 1/19/2009 3:03 PM John Machin apparently wrote:

It is not deprecated YET; see this:

http://docs.python.org/3.0/whatsnew/3.0.html#changes-already-present-in-python-2-6

PEP 3101: Advanced String Formatting. Note: the 2.6 description
mentions the format() method for both 8-bit and Unicode strings. In
3.0, only the str type (text strings with Unicode support) supports
this method; the bytes type does not. The plan is to eventually make
this the only API for string formatting, and to start deprecating the
% operator in Python 3.1.



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


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

2009-01-19 Thread Luis Zarrabeitia

Quoting "Russ P." :

> On Jan 19, 9:21 pm, Paul Rubin  wrote:
> > Bruno Desthuilliers  writes:
> > > The failure was because a module tested, QA'd and certified within a
> > > given context (in which it was ok to drop the builtin error handling)
> > > was reused in a context where it was not ok. And the point is exactly
> > > that : no *technology* can solve this kind of problem, because it is a
> > > *human* problem (in that case, not taking time to repass the whole
> > > specs / tests / QA process given context change).
> >
> 
> He says that "no *technology* can solve this kind of problem."
> 
> First of all, I'm not sure that's true. I think technology *could*
> have solved the problem -- e.g., Spark Ada, had it been properly
> applied. But that's beside the point. The point is that the problem
> had nothing to do with encapsulation. The rocket failed because a
> conversion was attempted to a data type that could not hold the
> required value. Am I missing something? I don't see what that has to
> do with encapsulation.
> 
> The logic seems to be as follows:
> 
> 1. Ada enforces data hiding.
> 2. Ada was used.
> 2. A major failure occurred.
> 
> Therefore:
> 
> Enforced data hiding is useless.


I don't think that was the logic... At least, it wasn't what I understood from
the example. We were talking at the time (or rather, you both were, as I think I
was still away from the thread) about QA versus static checks (as a superset of
'enforcement of data hiding').

Is not that those checks are useless, is that they make you believe you are
safe. Granted, you may be safe-er, but it may be better to know beforehand "this
is unsafe, I will check every assumption". The arianne 5 example cuts both ways:
messing with "internals" (not that internal in this case, but still) without
fully understanding the implications, and overly trusting the checks put in
place by the language. I don't know spark-ada, but the only thing I can think of
that would have prevented it is not purely technological. It would have been a
better documentation, where that particular assumption was written down. A
language can help you with it, perhaps spark-ada or eiffel or who-knows-what
could've forced the original developers to write that piece of documentation and
make the arianne 5 engineers notice it.

So, Arianne 5's problem had nothing to do with _enforced data hiding_. (Why do
you keep calling it 'encapsulation'?). It was a counterexample for your trust on
compiler checks.

Btw, what do you have against using pylint for detecting those 'access 
violations'?

> If that reasoning is sound, think about what else is useless.

I _hope_ that wasn't Bruno's reasoning. I don't want to switch sides on this
discussion :D.

Cheers,

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


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

2009-01-19 Thread Luis Zarrabeitia

Quoting Paul Rubin <"http://phr.cx"@NOSPAM.invalid>:

> Luis Zarrabeitia  writes:
> > > Luis Zarrabeitia  writes:
> > class ImmutableType(type): ...
> 
> Thanks for posting this, I haven't replied because I bookmarked the
> post for later study, but that was several days ago, so I just wanted
> to say that I'm still looking at it.  It's an area of Python that I've
> somewhat purposely stayed away from.

Hehe. Keep away - once you get dive into it, it'll be hard go get out. It's
really addictive :D

> > I use them, a lot, specially when writing decorators... Many times I
> > just want to 'mark' the decorated functions so I can inspect those
> > marks later.  I'd rather have a semi-private namespace for each pair
> > ([group of]calling function[s], object),
> 
> Right, thus the usefulness of a static tool that can find all those
> places where extra attributes are created.  Basically I can see three
> approaches to this question:

Btw, this thread inspired me to do another proof-of-concept stuff that I may be
using more seriously. Too bad I don't have anywhere to upload it right now...
Anyway, it looks like this: suppose I need to attach some attributes to the
object "x", but I don't want to do x.attr 

import namespaces # my module
class my_private_namespace(namespaces.Namespace): pass

def this_function_stores_the_attr(x):
ns = my_private_namespace(x)
ns.attr = 5 # I'm creating an attribute on the fly
# but at least I'm not touching x.

def this_function_reads_the_attr(x):
ns = my_private_namespace(x)
print ns.attr
 
> 1) Program in a style where you create and modify attributes all over
> the place willy-nilly, with no controls whatsoever, either automatic
> or stylistic.  From experience (it is a common style in Javascript) I
> can say this is a big mess and I think no experienced Python
> programmers recommend it.

Indeed. Though I don't consider myself 'experienced', I certainly don't
recommend it.

> 2) Have mandatory encapsulation like Java's, no way to escape.  Bruno
> and yourself vehemently object to this, Russ P seems to want it, my
> view is that it's not in the Python spirit, so I can accept the
> argument that those who really want this are better off choosing
> another language.

Btw, I noticed a funny side effect of my 'namespaces' module (needs a LOT of
work, this was the first time I touched weak references. I should find some
place to upload the module):

=
import namespaces

class public(namespaces.Namespace): pass
class private(namespaces.Namespace): # the initializer could check if
pass  # its called from outside the class. Performance penalty.

class A(object):
"""dummy class A, with one 'private' attribute x, and one
   normal 'attribute' x."""
def __init__(self):
self.x = id(self) # normal attr
pub = public(self)
pub.f = self.f
priv = private(self)
priv.x = "this is the private"
def f(self):
print "normal x: ", self.x
priv = private(self)
print "private x: ", priv.x


>>> a = A()
>>> dir(a)
['__class__', ,  'f', 'x']
>> a.f()
normal x: 147956684
private x: this is the private

>>> p = public(a)
>>> dir(p) # Look, there is no 'x' attribute!
['__class__', ,  'f']
>>> p.f() # but f still works!
normal x: 147956684
private x: this is the private
==

Of course, without checks in 'private', one could say priv = private(a); priv.x,
but the most interesting part, for me at least, was the ability to define a
'public' interface for a, that contains no attribute directly referencing the
object 'a' with its internals - only the names explicitly declared on the
'interface'. Indirectly... well, p.f.im_self will return back the 'a' object.

Bah, I'm ranting now. I just got carried away with my little experiment. Sorry.
Ah, and yes, metaclasses are dangerously addictive :D

> 3) Program in a style where creating new attributes outside the
> initializer is normally avoided by convention, but it is possible and
> sometimes desirable to break the convention.  This seems reasonable
> and Pythonic to me.  But, any place I break the convention, I should
> be able to say "I broke the convention here for such and such a
> reason".  And (this seems to be a bone of contention) IMO, it would be
> good to be able to audit a large codebase with a tool like Pylint, to
> automatically find all the places where such breakages occur.  Right
> now there seems to be no way to do that reliably, short of using
> something like your special metaclass instead of the standard one for
> just about everything.

Well, I agree. Each and every one of those convention-breakages should be well
documented, and pylint should be able to pick them up. Pylint does that already
(see example below), I don't know if it lets you "document" it explicitly. I
think Eclipse catches some of that stuff. My metaclass... shouldn't be used for
anything serious :D.

=== breaklint.py === (no, it didn't break pylint)
class A(o

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

2009-01-19 Thread Russ P.
On Jan 19, 9:21 pm, Paul Rubin  wrote:
> Bruno Desthuilliers  writes:
> > The failure was because a module tested, QA'd and certified within a
> > given context (in which it was ok to drop the builtin error handling)
> > was reused in a context where it was not ok. And the point is exactly
> > that : no *technology* can solve this kind of problem, because it is a
> > *human* problem (in that case, not taking time to repass the whole
> > specs / tests / QA process given context change).
>
> In this case it does nothing at all to support your arguments about
> the helpfulness or lack of helpfulness of strong encapsulation.  You
> may as well say that antibiotics are medically useless because they
> won't stop anyone from getting killed by a falling piano.

He says that "no *technology* can solve this kind of problem."

First of all, I'm not sure that's true. I think technology *could*
have solved the problem -- e.g., Spark Ada, had it been properly
applied. But that's beside the point. The point is that the problem
had nothing to do with encapsulation. The rocket failed because a
conversion was attempted to a data type that could not hold the
required value. Am I missing something? I don't see what that has to
do with encapsulation.

The logic seems to be as follows:

1. Ada enforces data hiding.
2. Ada was used.
2. A major failure occurred.

Therefore:

Enforced data hiding is useless.

If that reasoning is sound, think about what else is useless.


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


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

2009-01-19 Thread Paul Rubin
Bruno Desthuilliers  writes:
> Take some not-that-trivial projects like Zope/Plone. There are quite a
> few lines of code involved, and quite a lot of programmers worked on it.

Zope is about 375 KLOC[1], which I agree is not trivial, but by
today's standards, it's not all that large.  Zope also has 275 open
bugs, 6 of which are critical.[2] The Space Shuttle avionics (written
in the 1980's!) are 2 MLOC in which only 3 errors have been found
post-release.[3] I think "large software system" today means 100's of
MLOC.  FWIW, Zope has 20x as much code as Django--is that a good
thing!?

[1] http://www.peterbe.com/plog/size-Zope3,Django,TurboGears
[2] https://bugs.launchpad.net/zope3
[3] 
http://haacked.com/archive/2006/10/20/The_Misuse_of_the_Space_Shuttle_Analogy.aspx#11147
--
http://mail.python.org/mailman/listinfo/python-list


Re: *Advanced* Python book?

2009-01-19 Thread Banibrata Dutta
2009/1/17 Michele Simionato :
> "Expert Python Programming" by Tarek Ziadé is quite good and I wrote
> a review for it:
>
> http://www.artima.com/weblogs/viewpost.jsp?thread=240415

Excellent review.

-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Paul Rubin
Bruno Desthuilliers  writes:
> The failure was because a module tested, QA'd and certified within a
> given context (in which it was ok to drop the builtin error handling)
> was reused in a context where it was not ok. And the point is exactly
> that : no *technology* can solve this kind of problem, because it is a
> *human* problem (in that case, not taking time to repass the whole
> specs / tests / QA process given context change).

In this case it does nothing at all to support your arguments about
the helpfulness or lack of helpfulness of strong encapsulation.  You
may as well say that antibiotics are medically useless because they
won't stop anyone from getting killed by a falling piano.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Russ P.
On Jan 19, 8:32 pm, Luis Zarrabeitia  wrote:
> Quoting "Russ P." :
>
> > On Jan 19, 7:44 pm,  wrote:
> > > [removing david's message]
>
> > Why did you email your post to me? Did you really think I wanted to
> > see it in my inbox? I assure you I did not.
>
> Don't get mad at him... and don't take it personal. The reply-to header of 
> this
> mailing list (usenet users: for some of us, this is only a mailing list, and
> can't hope for more) points to the sender, and not the list. Many believe it 
> is
> the right thing to do, but if your mailer doesn't have a 'reply to list'
> function, like the one I'm using right now (Horde/Imp), your only option is to
> reply-to-all and then delete the original sender. I can't blame anyone for
> forgetting about the last part.

You're right. I shouldn't have gotten mad at him. I took his post as a
jab at me, but after thinking about it I realized it probably wasn't.
My apologies.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Russ P.
On Jan 19, 8:39 pm, Luis Zarrabeitia  wrote:

> If properties already
> let you change from attribute to method without affecting the caller, why do 
> you
> need a property that does nothing?

You don't. As I tried to explain in a earlier post (but one that you
may not have seen yet), that is apparently an implementation detail of
the way Scala implements properties. I probably should have never even
brought it up.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python resource management

2009-01-19 Thread Tim Arnold
"Philip Semanchuk"  wrote in message 
news:mailman.7530.1232375454.3487.python-l...@python.org...
>
> On Jan 19, 2009, at 3:12 AM, S.Selvam Siva wrote:
>
>> Hi all,
>>
>> I am running a python script which parses nearly 22,000 html files 
>> locally
>> stored using BeautifulSoup.
>> The problem is the memory usage linearly increases as the files are 
>> being
>> parsed.
>> When the script has crossed parsing 200 files or so, it consumes all  the
>> available RAM and The CPU usage comes down to 0% (may be due to 
>> excessive
>> paging).
>>
>> We tried 'del soup_object'  and used 'gc.collect()'. But, no 
>> improvement.
>>
>> Please guide me how to limit python's memory-usage or proper method  for
>> handling BeautifulSoup object in resource effective manner
>
> You need to figure out where the memory is disappearing. Try  commenting 
> out parts of your script. For instance, maybe start with a  minimalist 
> script: open and close the files but don't process them.  See if the 
> memory usage continues to be a problem. Then add elements  back in, making 
> your minimalist script more and more like the real  one. If the extreme 
> memory usage problem is isolated to one component  or section, you'll find 
> it this way.
>
> HTH
> Philip

Also, are you creating a separate soup object for each file or reusing one 
object over and over?
--Tim


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


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

2009-01-19 Thread Paul Rubin
Luis Zarrabeitia  writes:
> > Luis Zarrabeitia  writes:
> > > You *can* implement a metaclass that will remove the dynasmism from its
> > > instances
> import inspect
> class ImmutableType(type): ...

Thanks for posting this, I haven't replied because I bookmarked the
post for later study, but that was several days ago, so I just wanted
to say that I'm still looking at it.  It's an area of Python that I've
somewhat purposely stayed away from.

> But I see no _necessary_ harm on tacking extra attributes to an
> existing object - specially if you are going to use them pretty
> close to the creation.

> I use them, a lot, specially when writing decorators... Many times I
> just want to 'mark' the decorated functions so I can inspect those
> marks later.  I'd rather have a semi-private namespace for each pair
> ([group of]calling function[s], object),

Right, thus the usefulness of a static tool that can find all those
places where extra attributes are created.  Basically I can see three
approaches to this question:

1) Program in a style where you create and modify attributes all over
the place willy-nilly, with no controls whatsoever, either automatic
or stylistic.  From experience (it is a common style in Javascript) I
can say this is a big mess and I think no experienced Python
programmers recommend it.

2) Have mandatory encapsulation like Java's, no way to escape.  Bruno
and yourself vehemently object to this, Russ P seems to want it, my
view is that it's not in the Python spirit, so I can accept the
argument that those who really want this are better off choosing
another language.

3) Program in a style where creating new attributes outside the
initializer is normally avoided by convention, but it is possible and
sometimes desirable to break the convention.  This seems reasonable
and Pythonic to me.  But, any place I break the convention, I should
be able to say "I broke the convention here for such and such a
reason".  And (this seems to be a bone of contention) IMO, it would be
good to be able to audit a large codebase with a tool like Pylint, to
automatically find all the places where such breakages occur.  Right
now there seems to be no way to do that reliably, short of using
something like your special metaclass instead of the standard one for
just about everything.

Your example about decorators (used on classes that don't expect to be
wrapped by them) is a good one but narrow enough that there could be a
special arrangement for it in a hypothetical auditing tool.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 2:39 PM, Luis Zarrabeitia  wrote:
> This line would make a lot more sense if you were talking about Java's getters
> and setters, or about a language where accessing a property is different than
> accessing an attribute (which would make little sense). If properties already
> let you change from attribute to method without affecting the caller, why do 
> you
> need a property that does nothing?

My point exactly. Russ seems to agree with Python
but yet argue points for the sake of it. I'm not sure why :)

Having come from all kinda of programming backgrounds
and paradigms you learn to see the value in Python and the
kind of simplicity it has to offer. I will stand by my view
that there are many features of the traditional, strict
and academic features of the OO model that have little
practical value.

Python is a great mix of functional features, OO features
and has borrowed (what I believe) are the best of breed
features from all around.

One thing I find quite amazing is that we're having a discussion
over such low-level features of the OO model (and functional paradigm)
and how Python fits into it all ... And for what exactly ?

Russ - what is your point in all of this - You keep saying you don't have
time to waste with this - yet you keep making this thread grow
longer and longer and longer :)

As far as I'm concerned properties are just fancy functions to
retrieve and set attributes of an object. Consider the following
equivalent pieces of code:

#!/usr/bin/env python

from math import pi

class CircleA(object):

def __init__(self, radius):
self._radius = radius
self._area = pi * radius ** 2

def __getRadius(self):
return self._radius

def __setRadius(self, radius):
self._radius = radius
self._area = pi * radius ** 2

def __getArea(self):
return self._area

def __repr__(self):
return "" % (self.radius, self.area)

radius = property(__getRadius, __setRadius)
area = property(__getArea)

class CircleB(object):

def __init__(self, radius):
self.radius = radius
self.area = pi * radius ** 2

def setRadius(self, radius):
self.radius = radius
self.area = pi * radius ** 2

def __repr__(self):
return "" % (self.radius, self.area)

a = CircleA(1.5)
print a
a.radius = 2.0
print a

b = CircleB(1.5)
print b
b.radius = 2.0
print b

--

http://codepad.org/tpyGNhrZ

I'll give you a hint which one I prefer :)

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


Re: pep 8 constants

2009-01-19 Thread Ben Finney
Steven D'Aprano  writes:

> But regardless... yes, it is in my opinion Pythonic to use ALLCAPS
> to designate constants (by convention).

I agree, in general. Though I think I can count the number of times
I've wanted to use an ‘UPPER_CASE’-named constant in my code, on the
fingers of one foot.

> It isn't in PEP 8, but I don't think that matters unless PEP 8
> suggests a different convention.

It does recommend a contradictory convention:

Global Variable Names

  (Let's hope that these variables are meant for use inside one module
  only.)  The conventions are about the same as those for functions.

The conventions for functions are the familiar ‘lower_case’
conventions. This directly contradicts using ‘UPPER_CASE’ names.
Unless someone's going to argue that “Variable Names” doesn't apply to
constant names, even though Python doesn't make the distinction.

That said, I think upper-case name is a useful convention to
distinguish “this name binding is never expected to change” from the
common case, and wouldn't argue against its use. Perhaps I'd even
argue for an update to PEP 8 that endorses this as conventional.

-- 
 \ “I was born by Caesarian section. But not so you'd notice. It's |
  `\ just that when I leave a house, I go out through the window.” |
_o__)   —Steven Wright |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Luis Zarrabeitia

Quoting "Russ P." :

> In the circle example, properties are nice for guaranteeing
> consistency between the radius and the area, but they are not of much
> use if you decide later that the client should not be allowed to
> change either one. Well... I suppose you could define the setter to do
> nothing ... but you had better figure a way to notify the client about
> it.

Well, you could make it raise an exception. There was one C#1.0 class that did
this, Liskov substitution principle be damned (it was for a subtype). Very
frustrating. 

Once you decide for a public interface, you shouldn't change it... But, if you
absolutely have to do it, complain loudly and as soon as possible. In python,
I'd say that [a subclass of?] AttributeError would be the best solution for this
ill-advised situation.

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


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

2009-01-19 Thread Luis Zarrabeitia

Quoting "Russ P." :

> On Jan 19, 5:09 pm, Luis Zarrabeitia  wrote:
> 
> > Russ, I think _you_ are missing the point.
> > If the attribute is already public, why does it need properties? Why would
> a
> > programmer go to the trouble of adding them manually, just to get one level
> of
> > indirection for an already public attribute?
> 
> You don't understand the purpose of properties -- and you tell me that
> *I* am the one missing the point?

This line would make a lot more sense if you were talking about Java's getters
and setters, or about a language where accessing a property is different than
accessing an attribute (which would make little sense). If properties already
let you change from attribute to method without affecting the caller, why do you
need a property that does nothing?

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

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


Re: what's the point of rpython?

2009-01-19 Thread Paul Rubin
"Brendan Miller"  writes:
> As long as you can atomically increment and decrement an integer
> without locking you are pretty much done.

Most cpu's can't do that.

> For a reference implementation of lock free reference counting on all
> common platforms check out boosts implementation of shared_ptr (a
> reference counting smart pointer designed around multithreaded use
> cases).

That sounds very mysterious to me--are you sure it is intended for
multiprocessing and not just multiple threads on a single processor?
Do you have a url for the code?

> I see it the two trade offs that have to be made for GC vs alternative
> techniques. The "embarrassing pause" during compaction which makes it
> impossible to use for applications like interactive video display that
> can't halt to compact a several gigabyte heap without causing stutter,
> and the loose memory profile.

The embarassing pause is characteristic of a so-called "stop the
world" gc.  A gc where any pauses are guaranteed bounded in size
(preferably to a small value) is called a "real time" gc.  I believe
Cheng's algorithm is a real time alg but it's been a while since I
read that thesis.

Anyway, nobody programs interactive video in Python, and Python's ref
counting scheme is not real time since it may have to do arbitrarily
many decrefs when you release a large structure.

> As far as parallelism problems with GC go... the only ones I can
> imagine is that if you had a lot of threads going generating lots of
> garbage you would need to start to compact more frequently. Since
> compaction halts all threads, this could potentially cause very
> frequent compactions? Is that what you were getting at? 

I'm not sure what you're asking.  Parallelism is used for making
things go faster, but making things parallel usually complicates them.
A parallel realtime gc is sort of the holy grail.

Cheng's thesis is pretty readable as I remember, and discusses most of
these issues.  There is also a book by Appel about gc, but it's
perhaps a little bit dated by now.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Luis Zarrabeitia

Quoting "Russ P." :

> On Jan 19, 7:44 pm,  wrote:
> > [removing david's message]
> >
> Why did you email your post to me? Did you really think I wanted to
> see it in my inbox? I assure you I did not.

Don't get mad at him... and don't take it personal. The reply-to header of this
mailing list (usenet users: for some of us, this is only a mailing list, and
can't hope for more) points to the sender, and not the list. Many believe it is
the right thing to do, but if your mailer doesn't have a 'reply to list'
function, like the one I'm using right now (Horde/Imp), your only option is to
reply-to-all and then delete the original sender. I can't blame anyone for
forgetting about the last part.

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


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

2009-01-19 Thread Russ P.
On Jan 19, 8:17 pm, Luis Zarrabeitia  wrote:
> Quoting "Russ P." :
>
>
>
>
>
> > On Jan 19, 6:24 pm, "James Mills" 
> > wrote:
>
> > > Python programmers tend to not have a need for
> > > properties. Quite honestly they are a waste of time.
> > > They come from traditional OO approaches to software design
> > > (and mostly from the Java world).
>
> > With statements like that, it's no wonder you don't understand the
> > value of encapsulation.
>
> [snip]
>
> > If you didn't plan ahead and encapsulate the radius from the start,
> > properties allow you to save yourself and encapsulate it later without
> > breaking the client's code.
>
> Python programmers don't _need_ to plan ahead and encapsulate the radius from
> the start. That's the whole point. No clairvoyance needed. I kind of like 
> that.

And I like it too. I was trying to explain that to Mr. Mills, who
claimed that properties are "a waste of time."

Properties reduce the need for encapsulation, but they do not
eliminate it, particularly for large projects.

In the circle example, properties are nice for guaranteeing
consistency between the radius and the area, but they are not of much
use if you decide later that the client should not be allowed to
change either one. Well... I suppose you could define the setter to do
nothing ... but you had better figure a way to notify the client about
it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-19 Thread Carl Banks
On Jan 19, 8:00 pm, "Brendan Miller"  wrote:
> Maybe I'm missing something here but a lock free algorithm for
> reference counting seems pretty trivial. As long as you can atomically
> increment and decrement an integer without locking you are pretty much
> done.

You're missing that most of the platforms that Python supports can't
actually do this.  Keep in mind that it has to be atomic across all
cores.

(For Python to use such a technique, it would have to be doable on
every platform Python supports.  They aren't going to get rid of the
GIL for some platforms and not others.)


> For a reference implementation of lock free reference counting on all
> common platforms check out boosts implementation of shared_ptr (a
> reference counting smart pointer designed around multithreaded use
> cases).

I just looked at the boost documentation, which claims that multiple
asynchronous writes to the same shared_ptr results in undefined
behavior.  That will not suffice for Python reference counting.



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


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

2009-01-19 Thread Luis Zarrabeitia

Quoting Luis Zarrabeitia :

> 
> Quoting "Russ P." :
> 
> > On Jan 19, 6:24 pm, "James Mills" 
> > wrote:
> > 
> > > Python programmers tend to not have a need for
> > > properties. Quite honestly they are a waste of time.
> > > They come from traditional OO approaches to software design
> > > (and mostly from the Java world).
> > 
> > With statements like that, it's no wonder you don't understand the
> > value of encapsulation.
> > 
> [snip]
> > 
> > If you didn't plan ahead and encapsulate the radius from the start,
> > properties allow you to save yourself and encapsulate it later without
> > breaking the client's code.
> 
> Python programmers don't _need_ to plan ahead and encapsulate the radius
> from
> the start. That's the whole point. No clairvoyance needed. I kind of like
> that.

Oops. I didn't noticed we were agreeing on this last point.
Bad english... bad...

[btw, I highly doubt James doesn't understand the value of encapsulation. Don't
you mean "enforced data hiding" again?]

Cya!

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

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


Re: s=str(binary)

2009-01-19 Thread John Machin
On Jan 20, 12:54 pm, gert  wrote:
> How do you convert s back to binary data in python 3 so I can put in a
> sqlite blob ?
> Is there a build in function or do I need to use binascii ?
> byte(s) or bin(s) would make more sense but can not figure it out ?

Can't imagine why you would do str(binary_data) especially if you want
it back again ... however:

According to the fabulous manual:

str([object[, encoding[, errors]]])
Return a string version of an object, using one of the following
modes:
[snip]
When only object is given, this returns its nicely printable
representation. For strings, this is the string itself. The difference
with repr(object) is that str(object) does not always attempt to
return a string that is acceptable to eval(); its goal is to return a
printable string.

Hmm looks like (1) we need to do the dreaded eval() and (2) there's no
guarantee it will work.

>>> for i in range(256):
...blob = bytes([i])
...if eval(str(blob)) != blob:
...   print(i, blob, str(blob), eval(str(blob)))
...
>>> # no complaints!

Looks like it's going to work, but you better be rather sure that you
trust the source.

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


Re: what's the point of rpython?

2009-01-19 Thread Paul Rubin
"Brendan Miller"  writes:
> Maybe I'm missing something here but a lock free algorithm for
> reference counting seems pretty trivial. As long as you can atomically
> increment and decrement an integer without locking you are pretty much
> done.

What cpu's do you know of that can atomically increment and decrement
integers without locking?
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Russ P.
On Jan 19, 7:09 pm, "Russ P."  wrote:

> The benefit of automatically converting public data into properties, I
> assume, is to relieve the programmer of doing it manually. The
> programmer will obviously need to add any functionality when needed,
> but he does not need to create the function header.

Let me just correct this. As I said before, I haven't yet even used
Scala. The automatic generation of properties for public data members
is done automatically by the compiler and is apparently transparent to
the programmer. The programmer can then override the default
properties if he needs to add functionality. As far as the programmer
is concerned, this is really no different than Python properties. The
only difference is the way the two languages implement properties, not
the way they are used.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Luis Zarrabeitia

Quoting "Russ P." :

> On Jan 19, 6:24 pm, "James Mills" 
> wrote:
> 
> > Python programmers tend to not have a need for
> > properties. Quite honestly they are a waste of time.
> > They come from traditional OO approaches to software design
> > (and mostly from the Java world).
> 
> With statements like that, it's no wonder you don't understand the
> value of encapsulation.
> 
[snip]
> 
> If you didn't plan ahead and encapsulate the radius from the start,
> properties allow you to save yourself and encapsulate it later without
> breaking the client's code.

Python programmers don't _need_ to plan ahead and encapsulate the radius from
the start. That's the whole point. No clairvoyance needed. I kind of like that.

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

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


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

2009-01-19 Thread Luis Zarrabeitia

Quoting "Russ P." :

> One of the main benefits of properties is that they allow you to more
> safely put attributes in the public interface. If you later decide
> that the attribute shouldn't have been in the public interface, you
> can convert it to a property and make it do whatever you want it to
> do. That won't always save you, but sometimes it can.

That's true in Java, and python pre-'descriptor protocol'. 

It boggles me when I see python code with properties that only set and get the
attribute, or even worse, getters and setters for that purpose. In my university
they teach the students to write properties for the attributes in C# ("never
make a public attribute, always write a public property that just gets and sets
it"). I never understood that practice either, given that the syntax for
attribute access and property access in C# is exactly the same. (Could it be
that even if the syntax is the same, the compiled code differs? Don't know
enough about .NET to answer that).

I think I'm getting offtopic now. I better leave :D

[snip the rest of the email, as I agree with it]

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


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

2009-01-19 Thread Russ P.
On Jan 19, 7:44 pm,  wrote:
> >> Because frankly, that's how I read Russ' explanation for what Scala is
> >> doing. Have I missed something?
>
> coz he gets paid per line of code
>
> it's a mindless way of getting paid more for the same functionality...
>
> >> Well, I *thought* I did, and (unlike Bruno) I'm not hostile to the idea
> >> Russ is proposing. But I must admit it's not clear to me why Russ thinks
> >> it is a good idea to automatically turn this:
>
> >> class Parrot(object):
> >>     def __init__(self):
> >>         self.x = 1
>
> >> into this:
>
> >> class Parrot(object):
> >>     def __init__(self):
> >>         self._x = 1
> >>     def getx(self):
> >>         return self._x
> >>     def setx(self, value):
> >>         self._x = value
> >>     x = property(getx, setx)
>
>

Why did you email your post to me? Did you really think I wanted to
see it in my inbox? I assure you I did not.

And who "gets paid per line of code"? The whole point is that Scala
saves the programmer the trouble of writing that boilerplate code that
Java programmers write themselves, genius.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pep 8 constants

2009-01-19 Thread Steven D'Aprano
On Mon, 19 Jan 2009 19:11:16 -0800, Brendan Miller wrote:

>> Constants would be a nice addition in python, sure enough.
> 
> My original question was about PEP-8 and whether it is pythonic to use
> all caps to denote a variable that shouldn't be changed. More of a style
> question than a language question.
> 
> I actually think *enforcing* constantness seems to go against the grain
> of the language so to speek

Why? Python has an infinite number of constants. The only difference is 
that they are immutable objects, not names.

But regardless... yes, it is in my opinion Pythonic to use ALLCAPS to 
designate constants (by convention). It isn't in PEP 8, but I don't think 
that matters unless PEP 8 suggests a different convention.




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


Re: ifconfig in python

2009-01-19 Thread Дамјан Георгиевски
Something *like*  this could work:

myip = urllib2.urlopen('http://whatismyip.org/').read()

of course then you are depending on an external service, not a very 
reliable one even. But then again, you might create an internal service
like that yourself.

This cgi-bin shell code like this for ex:

#! /bin/sh
echo "Content-type: text/plain"
echo
echo "${REMOTE_ADDR}"


-- 
дамјан ( http://softver.org.mk/damjan/ )

Spammers scratch here with a diamond to find my address:
|||
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-19 Thread Brendan Miller
Maybe I'm missing something here but a lock free algorithm for
reference counting seems pretty trivial. As long as you can atomically
increment and decrement an integer without locking you are pretty much
done.

For a reference implementation of lock free reference counting on all
common platforms check out boosts implementation of shared_ptr (a
reference counting smart pointer designed around multithreaded use
cases).

>There are well known concurrent and parallel GC techniques that
Hmm... I didn't really mention poor parallelism as a problem of GC. As
I see it the two trade offs that have to be made for GC vs alternative
techniques. The "embarrassing pause" during compaction which makes it
impossible to use for applications like interactive video display that
can't halt to compact a several gigabyte heap without causing stutter,
and the loose memory profile.

Maybe the document you sent me addresses those, and I'd be interested
if it did. It's 150~ pages though so I haven't really had time to read
it yet.

As far as parallelism problems with GC go... the only ones I can
imagine is that if you had a lot of threads going generating lots of
garbage you would need to start to compact more frequently. Since
compaction halts all threads, this could potentially cause very
frequent compactions? Is that what you were getting at? I'd wondered
about that before, but didn't know for a fact whether it came up in
real world scenarios.
--
http://mail.python.org/mailman/listinfo/python-list


Re: braces fixed '#{' and '#}'

2009-01-19 Thread Tim Roberts
"Brendan Miller"  wrote:
>
>Yes, I also recently noticed the bug in python's parser that doesn't
>let it handle squigly braces and the bug in the lexer that makes white
>space significant. I'm surprised the dev's haven't noticed this yet.

It's very dangerous to make a post like this without including the smiley.
You're likely to get a mailbox full of "helpful" corrections...

;)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread david.lyon

>> Because frankly, that's how I read Russ' explanation for what Scala is
>> doing. Have I missed something?

coz he gets paid per line of code

it's a mindless way of getting paid more for the same functionality...

>> Well, I *thought* I did, and (unlike Bruno) I'm not hostile to the idea
>> Russ is proposing. But I must admit it's not clear to me why Russ thinks
>> it is a good idea to automatically turn this:
>>
>> class Parrot(object):
>>     def __init__(self):
>>         self.x = 1
>>
>> into this:
>>
>> class Parrot(object):
>>     def __init__(self):
>>         self._x = 1
>>     def getx(self):
>>         return self._x
>>     def setx(self, value):
>>         self._x = value
>>     x = property(getx, setx)
>>


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


Re: reading file to list

2009-01-19 Thread Xah Lee
On Jan 19, 4:49 pm, "Rhodri James" 
wrote:
> On Sun, 18 Jan 2009 08:31:15 -, Xah Lee  wrote:
> > On Jan 17, 10:25 am, Tino Wildenhain  wrote:
> >> > [[int(x) for x in line.split()] for line in open("blob.txt")]
>
> > Nice (python code).
>
> > Few comments:
>
> > • the above code is borderline of atypical. e.g. it is not a average
> > python code would produce or one'd seen in corporate python code.
>
> I can't imagine why not.

consider code produced by corporations, as opposed to with respect to
some academic or philsophical logical analysis. Looked in another way,
consider if we can compile stat of all existing pyhton code used in
real world, you'll find the above style is rarely used.

in a logical analysis, each lang fanatics will actively sell certain
style of construction, but that's just not the way code in the real
world are. Ample examples can be found especially in other cultish
lang groups such as lisp, perl, etc. (less of this phenomenon is found
in lang like php, javascript, java, C, where the lang simple don't
create fancy constructions in the name of improvement or esthetics or
weird philosophy in the first place.)

> > • voodoo like the above makes me dislike python. To me, the one
> > advantage of python is its clarity enforced by its syntax.
> > Specifically, the forced indendation and quite simple semantics.
> > However, the way i've seen Guido's propensities and how python 3 is
> > moving to, it is becoming more mumbo jumbo of computer sciency OOP
> > jargons with syntax soup. (with iterators, enumerators, list
> > comprehension... shits forced upon the users)
>
> > The above line illustrate well the ad hoc syntax soup nature python is
> > moving into.
>
> To a native English speaker, it illustrates entirely the reverse.
> List comprehension is actually quite a linguistically natural way
> to express the iterative construction of a list.

computer lang is not human lang. In argument based on human lang, you
have AppleScript, Perl, which are un-readable or cumbersome to most
programers. Even with human lang, if you know linguistics to some
extend, you know that natural lang is a complete wortheless mess in
every aspect with respect to “design” qualities.

  Xah
∑ http://xahlee.org/

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


Re: function to find the modification date of the project

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 1:22 PM, Joe Strout  wrote:
> Any comments on the functioning and platform-independence of the code?

Make it simpler :)

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


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

2009-01-19 Thread Russ P.
On Jan 19, 6:24 pm, "James Mills" 
wrote:

> Python programmers tend to not have a need for
> properties. Quite honestly they are a waste of time.
> They come from traditional OO approaches to software design
> (and mostly from the Java world).

With statements like that, it's no wonder you don't understand the
value of encapsulation.

With encapsulation (whether enforced or voluntary), no one has the
"need" for properties. You can always just provide functions to do the
same job. What properties do is to essentially make the function call
simpler for the client. The client just sets the radius of the circle,
and, lo and behold, the area gets changed automatically and
consistently.

If you didn't plan ahead and encapsulate the radius from the start,
properties allow you to save yourself and encapsulate it later without
breaking the client's code.

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


Re: function to find the modification date of the project

2009-01-19 Thread Joe Strout

Terry Reedy wrote:

Yes, and presumably if some power user did this, then that would be 
the intended effect.  Not sure why they'd do that, but they must have 
a good reason -- who am I to stop them?


What if a curious user simple looks at a file with an editor and saves 
it without change?


You can't do that, on the Mac at least...

Or changes it inconsequentially? Or makes copy to 
x.py.orig, edits and plays with original, and when done renames 
x.py.orig to x.py.  Or any such thing (which I have done in 
Pythonxy/Lib) without any intention of changing version date?


Then the About box will show, quite correctly, that the app was mucked 
with at that date, and when they call me up and complain, and I ask them 
to read me the contents of the About box, I can know right away that 
they've probably broken something (no matter how inconsequential they 
believed their change to be), and tell them to re-download it.


But really, this is NOT going to happen.  These users wouldn't even know 
how to open the app bundle to find the Python files.


Any comments on the functioning and platform-independence of the code?

Thanks,
- Joe


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


Re: pep 8 constants

2009-01-19 Thread Brendan Miller
> Constants would be a nice addition in python, sure enough.

My original question was about PEP-8 and whether it is pythonic to use
all caps to denote a variable that shouldn't be changed. More of a
style question than a language question.

I actually think *enforcing* constantness seems to go against the
grain of the language so to speek
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Russ P.
On Jan 19, 6:24 pm, Steven D'Aprano
 wrote:
> On Mon, 19 Jan 2009 18:07:50 -0800, Russ P. wrote:
> > On Jan 19, 5:09 pm, Luis Zarrabeitia  wrote:
>
> >> Russ, I think _you_ are missing the point. If the attribute is already
> >> public, why does it need properties? Why would a programmer go to the
> >> trouble of adding them manually, just to get one level of indirection
> >> for an already public attribute?
>
> > You don't understand the purpose of properties -- and you tell me that
> > *I* am the one missing the point?
>
> Well, I *thought* I did, and (unlike Bruno) I'm not hostile to the idea
> Russ is proposing. But I must admit it's not clear to me why Russ thinks
> it is a good idea to automatically turn this:
>
> class Parrot(object):
>     def __init__(self):
>         self.x = 1
>
> into this:
>
> class Parrot(object):
>     def __init__(self):
>         self._x = 1
>     def getx(self):
>         return self._x
>     def setx(self, value):
>         self._x = value
>     x = property(getx, setx)
>
> Because frankly, that's how I read Russ' explanation for what Scala is
> doing. Have I missed something?
>
> --
> Steven

Whoops, I accidentally hit send on the last post.

One of the main benefits of properties is that they allow you to more
safely put attributes in the public interface. If you later decide
that the attribute shouldn't have been in the public interface, you
can convert it to a property and make it do whatever you want it to
do. That won't always save you, but sometimes it can.

As a trivial example, suppose you have a circle class with public
attributes of radius and area. You later realize that it is unwise to
let the user change one without changing the other, leaving them
inconsistent. With properties, you can convert them each to a property
and write functions to force consistency.

The benefit of automatically converting public data into properties, I
assume, is to relieve the programmer of doing it manually. The
programmer will obviously need to add any functionality when needed,
but he does not need to create the function header.

I don't know the implications for efficiency in Scala. Perhaps there
is a slight cost for one level of indirection. But please recall that
public data is supposed to be rarely if ever used anyway. Unlike some
folks here, the Scala folks understand the value of encapsulation and
data hiding.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ifconfig in python

2009-01-19 Thread Mark Wooding
"James Mills"  writes:

> On Tue, Jan 20, 2009 at 10:28 AM, Nehemiah Dacres  
> wrote:
>> Is ther an easy way to get the resolved ip address of the machine a
>> script is running on? socket.gethostbyname(socket.gethostname) has
>> only returned the ip address of my loop back interface ... not very
>> usefull.
>
> That's because your /etc/hosts resolves your hostname to 127.0.0.1 :)

This just illustrates the real problem with the OP's question.  The idea
of `/the/ ... ip address of the machine' is simply ill-formed.

An Internet host has at least two IP addresses -- one of them is
127.0.0.1 -- and may have many more.  The laptop I'm typing on right now
has three; the server next door has four.  Network interfaces may have
multiple addresses associated with them (and hosts using the weak
end-system model consider the addresses as referring to the host in
general rather than a specific interface anyway), and several interfaces
might have the same address.

Sorry.  Life's more complicated than you'd like it to be.

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


Re: tasklet library based on PEP 0342

2009-01-19 Thread charlie137
On Jan 20, 6:37 am, Terry Reedy  wrote:
> charlie...@gmail.com wrote:
> > Using new features of python generators, as described in PEP 0342, it
> > is possible to write some sort of "tasklets" in a maner very similar
> > to stackless python, but running on cpython. For example :
>
> > @tasklet
> > def my_task():
> >     yield Timer(10)
> >     yield "result"
>
> > @tasklet
> > def other_task():
> >     result = yield my_task()
>
> > other_task().start(callback=on_return)
>
> > I wrote an implementation of this in the scope of an open source
> > project for openmoko [0], there is also an other very similar
> > implementation from the kiwi project [1].
>
> > This kind of tool is very useful, but unfortunately there is no
> > standard library that would provide a unified way to use it
> > independently of the underlying event loop.
>
> > Does someone know if a similar library could eventually be added into
> > python standard libraries ? Would it be accepted as a PEP ?
>
> Start by listing your module/library onhttp://pypi.python.org/pypi
> To ever get in the stdlib, it must be tested, used by several different
> people, the best of its type, and relative stable.

I am afraid my implementation passes none of those requirement.
I will send a message to the python idea mailing list though. Thanks
for the answers.

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


Re: ifconfig in python

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 12:48 PM, Ned Deily  wrote:
> Also, since the subject is on my brain at the moment, how to find "the
> address" is not the right question to ask.  These days most systems have
> multiple network interfaces (Ethernet, WiFi, dialup, et al) running
> multiple protocols, like IPv4 and IPv6.  In general, there is no *one*
> IP address of a machine; often there are many.  Ignoring that fact can
> lead to subtle bugs, like the one causing a urllib2 regression test
> failure that I've been squashing today!

I agree.

Nehemiah:

What is the problem you're solving ?

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


Re: Two questions about style and some simple math

2009-01-19 Thread John Machin
On Jan 20, 12:15 pm, Spoofy  wrote:
> Hello everybody!
>
> Though I'm a hobby programmer for years now (mainly small hackery
> things) I still have big problems getting "real" things to work.
>
> I'm currently trying to write a simple RPG and have problems with
> the following:
>
> 1.
>
> Characters have a "courage" attribute that basically determins who
> has the first attack in a fight. After some trying, I came up with
> this (sorry, not really working code, but what I made from
> interactive experimentation):
>
> def first_attack(player1,  player2):
>      diff = player1.attributes.courage - player2.attributes.courage
>      players = (player,  player2)
>      return players[diff + random.randint(-diff,  diff) < 0]
>
> To make it more realistic, I randomized it a little bit and this
> seems to work for low courage values. But when the courage values
> are high (100 and such) it fails (the chance to have the first
> attack drops the higher the values are). My math is really bad and I
> have problems to understand what's happenning here. I suspect the
> greater range for randint() is the problem, but I don't really get why.

Are you 100% sure that the above code is what you have been running?

For a start, the result of that code depends only on "diff" which is
the difference between the two courages -- it should not be influenced
by whether the courages are (say) about 10 or about 100.

If player1 is more aggro than player2, then diff will be positive.
Let's say it's 20. The lowest possible value returned by random.randint
(-20, 20) will be -20. Then 20 + (-20) is zero. so 0 < 0 is False, and
player 1 will always be chosen. This happens for any positive value of
diff, even 1.

If the diff is zero, then again you get 0 < 0, and player1 will always
be chosen.

If the diff is negative, the world blows up; for diff == -10, you get
this:
ValueError: empty range for randrange() (10,-9, -19)

I think that you need to take the range of the courage values into
account. You need to scale the randomisation so that you get
believable outcomes. If the players have equal courage, there should
be a 50% chance that player2 hits first. If one has maximal courage
and the other has zero, then the maximal one should have 100% chance
of hitting first. For example:

>>> def choosep2(diff, maxc):
...assert abs(diff) <= maxc
...return random.randint(-maxc, maxc-1) >= diff
...
>>> def simulate(diff, maxc):
...return sum(choosep2(diff, maxc) for _ in range(100))
...
>>> simulate(0, 50)
50
>>> simulate(0, 50)
47
>>> simulate(0, 50)
43
>>> simulate(49, 50)
1
>>> simulate(-49, 50)
100
>>>

You may want to choose a probability distribution that's a bit more
bell-shaped than roadkill-shaped, but whatever you do you should check
that it's behaving plausibly.

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


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

2009-01-19 Thread Russ P.
On Jan 19, 6:24 pm, Steven D'Aprano
 wrote:
> On Mon, 19 Jan 2009 18:07:50 -0800, Russ P. wrote:
> > On Jan 19, 5:09 pm, Luis Zarrabeitia  wrote:
>
> >> Russ, I think _you_ are missing the point. If the attribute is already
> >> public, why does it need properties? Why would a programmer go to the
> >> trouble of adding them manually, just to get one level of indirection
> >> for an already public attribute?
>
> > You don't understand the purpose of properties -- and you tell me that
> > *I* am the one missing the point?
>
> Well, I *thought* I did, and (unlike Bruno) I'm not hostile to the idea
> Russ is proposing. But I must admit it's not clear to me why Russ thinks
> it is a good idea to automatically turn this:
>
> class Parrot(object):
>     def __init__(self):
>         self.x = 1
>
> into this:
>
> class Parrot(object):
>     def __init__(self):
>         self._x = 1
>     def getx(self):
>         return self._x
>     def setx(self, value):
>         self._x = value
>     x = property(getx, setx)
>
> Because frankly, that's how I read Russ' explanation for what Scala is
> doing. Have I missed something?
>
> --
> Steven

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


Re: Relax Syntax for Augmented Arithmetic?

2009-01-19 Thread Mark Wooding
Steven D'Aprano  writes:

> There's a practical reason too. You create a new Foo instance, mutate
> it with the augmented assignment operator, and then a tenth of a
> millisecond later the garbage collector throws it away because it has
> a reference count of zero.

Only in this specific example.  A function can easily return a
well-known object, which it's sensible to mutate.

Besides,

class mumble (object): pass
mumble().foo = 1

is accepted without fuss, and is just as useless.

I think I see the confusion here.

  * Python assignment (`=') is fairly simple.  The left-hand side is
analyzed syntactically: if it's a plain name then the variable it
denotes is modified; otherwise an appropriate method is invoked to
mutate some object.

  * Python augmented-assignment (`+=', for example) is inconsistent.
Depending on what type of object the left-hand side evaluates to, it
may /either/ mutate that object, /or/ assign a new value to the
expression.

What do I mean?  Well, consider this function.

def assg(x, y):
  x = y

Under no circumstances does calling this function have any effect (other
than wasting time and memory).  But:

def aug(x, y):
  x += y

Calling this function might or might not have an observable effect,
depending on the type of x.  For example,

x = 5
aug(x, 3)

is useless, but

x = [1, 2, 3]
aug(x, [4])

is not.

The `aug' function can be used to bypass the syntactic restriction on
augmented assignment, where it makes sense:

  aug(func(), 17)

is always syntactically valid, and may or may not be useless depending
on the type of thing returned by `func'.

The Python language refuses to let the programmer write something which
is (a) possibly meaningful, and (b) possibly useful because augmented
assignment inherits the syntactic restriction of simple assignment that
the left-hand side expression designate a `place' -- i.e., one of the
things that there's a rule for assigning to, e.g., VAR, EXPR[INDEX],
EXPR.ID -- because it /might/ need to perform such an assignment, though
it might not.

My personal view is that augmented-assignment operators which work by
mutation rather than assignment (e.g., `+=' on lists, rather than `+='
on numbers) are one of Python's least pleasant warts.  But if they're
going to exist then I think

list() += [1]

ought to be valid syntax, since semantically it's actually clear what it
should do (namely, construct a fresh empty list, append a `1' to it, and
then throw the whole thing away).  Of course,

tuple() += 1,

is still meaningless, and ought to be an error.  Of course, this removes
a static error-check, but if we were petty about getting all our errors
at compile time we wouldn't be writing in Python in the first place.

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


Re: ifconfig in python

2009-01-19 Thread Ned Deily
In article 
,
 "James Mills"  wrote:

> On Tue, Jan 20, 2009 at 10:28 AM, Nehemiah Dacres  
> wrote:
> > Is ther an easy way to get the resolved ip address of the machine a script
> > is running on? socket.gethostbyname(socket.gethostname) has only returned
> > the ip address of my loop back interface ... not very usefull.
> 
> That's because your /etc/hosts resolves
> your hostname to 127.0.0.1 :)
> 
> And no I know of no "easy" way cross
> platform way. Perhaps parsing the output
> of ifconfig itself ?

Also, since the subject is on my brain at the moment, how to find "the 
address" is not the right question to ask.  These days most systems have 
multiple network interfaces (Ethernet, WiFi, dialup, et al) running 
multiple protocols, like IPv4 and IPv6.  In general, there is no *one* 
IP address of a machine; often there are many.  Ignoring that fact can 
lead to subtle bugs, like the one causing a urllib2 regression test 
failure that I've been squashing today!

-- 
 Ned Deily,
 n...@acm.org

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


Re: Event Handling and Signal-Slot Mechanism

2009-01-19 Thread Steven Woody
On Tue, Jan 20, 2009 at 1:03 AM, BlueBird  wrote:
> On Jan 19, 4:10 am, Steven Woody  wrote:
>> Hi,
>>
>> Python has Signal-Slot mechanism,
>
> Python does not have signal/slot mechanism. You are talking about the
> Qt toolkit, which is initially a (nice) C++ toolkit, available also in
> python via the PyQt wrapper.
>
> Signal/slots were introduced by Qt to make C++ gui programming easier.
> Signal/slots basically provides a very easy way to implement the
> observer/consumer design pattern, with only 2 or 3 lines of code (as
> opposed to one or two classes in java for example).
>
> Python itself does not have signal/slots but the it's very easy to
> emulate them using the Python language. In C++ however, it's tricky to
> do signal/slots in pure C++ and this addition is one of the reason
> that programming GUI in Qt is nice (personal opinion obviously).
>
> To comne back to your question:
>
>> why he still need another mechanism
>> Event Handling?
>
> This is actually a Qt question: why have event handling for some
> things, and signal/slot for some others ?
>
> My opinion on the debate:
> - signal/slot add an overhead of one class to every QObject class, and
> 3 method calls when emitting a signal (if I remember Qt documentation
> correctly). For some real-time tasks, like repainting the screen,
> every microseconds must be saved and sparing 3 method calls is a good
> idea.
> - since a GUI application is fundamentally an event driven system, the
> event stuff has to be there anyway.
> - signal/slot is very convenient for data exchange between widgets but
> I think it would be overkill to use it everywhere. Event propagation
> is a nice design as well.
>
> Now, if you want to discuss this further, I suggest to go to Qt
> interest ( http://lists.trolltech.com/qt-interest/ ) which is
> dedicated to discussion around Qt.
>
> cheers,
>
> Philippe
> --
> http://mail.python.org/mailman/listinfo/python-list
>

So much thanks, Philippe!
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-01-19 Thread Steven D'Aprano
On Mon, 19 Jan 2009 18:07:50 -0800, Russ P. wrote:

> On Jan 19, 5:09 pm, Luis Zarrabeitia  wrote:
> 
>> Russ, I think _you_ are missing the point. If the attribute is already
>> public, why does it need properties? Why would a programmer go to the
>> trouble of adding them manually, just to get one level of indirection
>> for an already public attribute?
> 
> You don't understand the purpose of properties -- and you tell me that
> *I* am the one missing the point?


Well, I *thought* I did, and (unlike Bruno) I'm not hostile to the idea 
Russ is proposing. But I must admit it's not clear to me why Russ thinks 
it is a good idea to automatically turn this:

class Parrot(object):
def __init__(self):
self.x = 1


into this:

class Parrot(object):
def __init__(self):
self._x = 1
def getx(self):
return self._x
def setx(self, value):
self._x = value
x = property(getx, setx)


Because frankly, that's how I read Russ' explanation for what Scala is 
doing. Have I missed something? 



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


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

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 12:07 PM, Russ P.  wrote:
>> Russ, I think _you_ are missing the point.
>> If the attribute is already public, why does it need properties? Why would a
>> programmer go to the trouble of adding them manually, just to get one level 
>> of
>> indirection for an already public attribute?
>
> You don't understand the purpose of properties -- and you tell me that
> *I* am the one missing the point?

Russ, he is correct. Your opinions are not founded on solid knowledge.

Python programmers tend to not have a need for
properties. Quite honestly they are a waste of time.
They come from traditional OO approaches to software design
(and mostly from the Java world).

> I give up. I really don't have time for this.

You've said that before :)

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


modify IDLE?

2009-01-19 Thread Brian Blais

Hello,

I was wondering if there is a simple way to modify IDLE, adding or  
replacing menus?  I haven't dug into the source code yet, but was  
wondering if anyone else has done something like this.  I have a  
couple of projects that require users to write python code (or very  
similar to python code) which is then run either in a completely  
different interpreter, or pre-processed and run.  Right now, I just  
make those programs load files, but it would be nice if somehow a  
version of IDLE could pass the current buffer to my program instead  
of the built-in interpreter.  Is mucking around with the IDLE code  
something easy, or a bit of a challenge?



thanks,

Brian Blais

--
Brian Blais
bbl...@bryant.edu
http://web.bryant.edu/~bblais



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


Re: Two questions about style and some simple math

2009-01-19 Thread Mensanator
On Jan 19, 7:44 pm, "Rhodri James" 
wrote:
> On Tue, 20 Jan 2009 01:15:47 -, Spoofy  wrote:
> > Hello everybody!
>
> > Though I'm a hobby programmer for years now (mainly small hackery  
> > things) I still have big problems getting "real" things to work.
>
> > I'm currently trying to write a simple RPG and have problems with the  
> > following:
>
> > 1.
>
> > Characters have a "courage" attribute that basically determins who has  
> > the first attack in a fight. After some trying, I came up with this  
> > (sorry, not really working code, but what I made from interactive  
> > experimentation):
>
> > def first_attack(player1,  player2):
> >      diff = player1.attributes.courage - player2.attributes.courage
> >      players = (player,  player2)
> >      return players[diff + random.randint(-diff,  diff) < 0]
>
> > To make it more realistic, I randomized it a little bit and this seems  
> > to work for low courage values. But when the courage values are high  
> > (100 and such) it fails (the chance to have the first attack drops the  
> > higher the values are). My math is really bad and I have problems to  
> > understand what's happenning here. I suspect the greater range for  
> > randint() is the problem, but I don't really get why.
>
> > Any tips would be greatly appreciated.
>
> This is always going to select player1 (assuming you fix the typo of
> "player" for "player1"!).  The most negative number that the call to
> randint can produce is "-diff", so "diff + randint()" is at least
> "diff + -diff", which is zero and hence never less than zero.
>
> Surely in any case you don't want an expression based on the difference,
> since that would give you the same chance of having the first attack no
> matter what the levels of courage actually were, which can't be right.

Why? Isn't it possible some attributes are relative rather than
absolute?

>
>
>
>
>
> > 2.
>
> > For maintaining the character attributes I creates a seperate class. I  
> > wonder weather this is an "overuse" of OO (instead of just making the  
> > attributes plain variables of the Char class) and if the way I wrote  
> > this is OK (somehow this looks cool to me but maybe too "showy"?)
>
> > class Attributes(object):
> >      ATTRIBUTES = {"attack": 0, "defence": 0, "ability": 0, "courage":  
> > 0, "condition": 0}
> >      def __init__(self, **kwargs):
> >          self.__dict__.update(self.ATTRIBUTES)
> >          for arg in kwargs:
> >              if arg not in self.ATTRIBUTES:
> >                  raise ValueError("Unkown character attribute '%s'" %  
> > arg)
> >              self.__dict__[arg] = kwargs[arg]
>
> It's not necessarily a bad idea to have your character attributes in a
> separate class, but do you really need to prevent use of other class
> attribute names (sorry, the terminology crossover is inherently
> confusing) so much?  Unless you think there's a serious danger of
> trying to add new character attributes on the fly, I think it's
> overkill.
>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

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


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

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

> Russ, I think _you_ are missing the point.
> If the attribute is already public, why does it need properties? Why would a
> programmer go to the trouble of adding them manually, just to get one level of
> indirection for an already public attribute?

You don't understand the purpose of properties -- and you tell me that
*I* am the one missing the point?

I give up. I really don't have time for this.
--
http://mail.python.org/mailman/listinfo/python-list


s=str(binary)

2009-01-19 Thread gert
How do you convert s back to binary data in python 3 so I can put in a
sqlite blob ?
Is there a build in function or do I need to use binascii ?
byte(s) or bin(s) would make more sense but can not figure it out ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Two questions about style and some simple math

2009-01-19 Thread MRAB

Spoofy wrote:

Hello everybody!

Though I'm a hobby programmer for years now (mainly small hackery 
things) I still have big problems getting "real" things to work.


I'm currently trying to write a simple RPG and have problems with the 
following:


1.

Characters have a "courage" attribute that basically determins who has 
the first attack in a fight. After some trying, I came up with this 
(sorry, not really working code, but what I made from interactive 
experimentation):


def first_attack(player1,  player2):
diff = player1.attributes.courage - player2.attributes.courage
players = (player,  player2)
return players[diff + random.randint(-diff,  diff) < 0]

To make it more realistic, I randomized it a little bit and this seems 
to work for low courage values. But when the courage values are high 
(100 and such) it fails (the chance to have the first attack drops the 
higher the values are). My math is really bad and I have problems to 
understand what's happenning here. I suspect the greater range for 
randint() is the problem, but I don't really get why.


Any tips would be greatly appreciated.


[snip]

Try:

def first_attack(player1,  player2):
total_courage = player1.attributes.courage + player2.attributes.courage
players = (player,  player2)
return players[random.randrange(0, total_courage) < 
player1.attributes.courage]


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


Re: Two questions about style and some simple math

2009-01-19 Thread Rhodri James

On Tue, 20 Jan 2009 01:15:47 -, Spoofy  wrote:


Hello everybody!

Though I'm a hobby programmer for years now (mainly small hackery  
things) I still have big problems getting "real" things to work.


I'm currently trying to write a simple RPG and have problems with the  
following:


1.

Characters have a "courage" attribute that basically determins who has  
the first attack in a fight. After some trying, I came up with this  
(sorry, not really working code, but what I made from interactive  
experimentation):


def first_attack(player1,  player2):
 diff = player1.attributes.courage - player2.attributes.courage
 players = (player,  player2)
 return players[diff + random.randint(-diff,  diff) < 0]

To make it more realistic, I randomized it a little bit and this seems  
to work for low courage values. But when the courage values are high  
(100 and such) it fails (the chance to have the first attack drops the  
higher the values are). My math is really bad and I have problems to  
understand what's happenning here. I suspect the greater range for  
randint() is the problem, but I don't really get why.


Any tips would be greatly appreciated.


This is always going to select player1 (assuming you fix the typo of
"player" for "player1"!).  The most negative number that the call to
randint can produce is "-diff", so "diff + randint()" is at least
"diff + -diff", which is zero and hence never less than zero.

Surely in any case you don't want an expression based on the difference,
since that would give you the same chance of having the first attack no
matter what the levels of courage actually were, which can't be right.



2.

For maintaining the character attributes I creates a seperate class. I  
wonder weather this is an "overuse" of OO (instead of just making the  
attributes plain variables of the Char class) and if the way I wrote  
this is OK (somehow this looks cool to me but maybe too "showy"?)


class Attributes(object):
 ATTRIBUTES = {"attack": 0, "defence": 0, "ability": 0, "courage":  
0, "condition": 0}

 def __init__(self, **kwargs):
 self.__dict__.update(self.ATTRIBUTES)
 for arg in kwargs:
 if arg not in self.ATTRIBUTES:
 raise ValueError("Unkown character attribute '%s'" %  
arg)

 self.__dict__[arg] = kwargs[arg]


It's not necessarily a bad idea to have your character attributes in a
separate class, but do you really need to prevent use of other class
attribute names (sorry, the terminology crossover is inherently
confusing) so much?  Unless you think there's a serious danger of
trying to add new character attributes on the fly, I think it's
overkill.

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


Two questions about style and some simple math

2009-01-19 Thread Spoofy

Hello everybody!

Though I'm a hobby programmer for years now (mainly small hackery 
things) I still have big problems getting "real" things to work.


I'm currently trying to write a simple RPG and have problems with 
the following:


1.

Characters have a "courage" attribute that basically determins who 
has the first attack in a fight. After some trying, I came up with 
this (sorry, not really working code, but what I made from 
interactive experimentation):


def first_attack(player1,  player2):
diff = player1.attributes.courage - player2.attributes.courage
players = (player,  player2)
return players[diff + random.randint(-diff,  diff) < 0]

To make it more realistic, I randomized it a little bit and this 
seems to work for low courage values. But when the courage values 
are high (100 and such) it fails (the chance to have the first 
attack drops the higher the values are). My math is really bad and I 
have problems to understand what's happenning here. I suspect the 
greater range for randint() is the problem, but I don't really get why.


Any tips would be greatly appreciated.

2.

For maintaining the character attributes I creates a seperate class. 
I wonder weather this is an "overuse" of OO (instead of just making 
the attributes plain variables of the Char class) and if the way I 
wrote this is OK (somehow this looks cool to me but maybe too "showy"?)


class Attributes(object):
ATTRIBUTES = {"attack": 0, "defence": 0, "ability": 0, 
"courage": 0, "condition": 0}

def __init__(self, **kwargs):
self.__dict__.update(self.ATTRIBUTES)
for arg in kwargs:
if arg not in self.ATTRIBUTES:
raise ValueError("Unkown character attribute '%s'" 
% arg)

self.__dict__[arg] = kwargs[arg]


Again, I appreciate any tips. I you need more code (for the bigger 
picture or such), just ask.


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


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

2009-01-19 Thread Luis Zarrabeitia

Quoting "Russ P." :

> On Jan 19, 7:13 am, Bruno Desthuilliers  42.desthuilli...@websiteburo.invalid> wrote:
> 
> > I must be missing the point : if it's a public attribute, it doesn't
> > need a "property" ? I guess we use the same words for different things
> here.
> 
> Yes, you are missing more than one point.
> 
> Scala automatically converts public data members into properties,
> apparently to save the programmer the trouble of doing it manually. If
> you are interested, I'm sure you can find publicly available
> information on it.

Russ, I think _you_ are missing the point.
If the attribute is already public, why does it need properties? Why would a
programmer go to the trouble of adding them manually, just to get one level of
indirection for an already public attribute?

> > I definitively wouldn't bet my ass on language-level access restriction
> > to protect software from fraud or sabotage.
> 
> You're missing the point here too. I'll try one more time to explain
> it.

And I think you are conflating the idea of "private" as in "secret information
that should not be known by the _public_" and "private" as in "static safeguards
enforced by the compiler to prevent accidents" [and you are missing the third,
"compiler feature to prevent namespace pollution without having to use extremely
unlikely variable names", i.e, self.__x in python].

No wonder you can't get Bruno's point. For the second, static checks to prevent
accidents, you have pylint. For the first, not only you are using the wrong
tool, but you are barking at python for not having it. Assuming that pylint is
perfect (big assumption, but it is up to you to prove where it fails), what
would be the difference between only accepting/running "pylint-authorized code"
and the enforced hiding you desire?

This thread is starting to remind me of a professor of mine, who once claimed
that python didn't have private attributes because it "is opensource and anyone
can see the source code anyway", and the obvious confusion of his students ("why
should I make my entrypoint '_public_ static void main', if it is _my_
sourcecode and I don't want to share it?").

What you want is not enforced data hiding. You want something actually designed
to try to prevent abuses from hostile programmers - go use .Net or Java, who
attempt to do that (I don't know with what level of success, but they at least
provide you the 'locks' and 'police' that you need). Or better yet, write a
proposal about how to implement code trust in Python. I'll support you on that
one, and I think many others will. But if you keep presenting data hiding as a
solution to that problem... I doubt that you will be heard.

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


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


Re: function to find the modification date of the project

2009-01-19 Thread Scott David Daniels

Joe Strout wrote:
This isn't a question, but something I thought others may find useful 
(and if somebody can spot any errors with it, I'll be grateful).


We had a case recently where the client was running an older version of 
our app, and didn't realize it.  In other languages I've avoided this by 
displaying the compile date in the About box, but of course Python 
doesn't really have a meaningful compile date.  So, instead we're now 
displaying the latest modification date of any .py file in the project. 
 Here's the function that finds that:



def lastModDate():
"Get the latest modification date (as a string) of any .py file in 
this project."

import os, time
latest = 0
dir = os.path.dirname(__file__)
if dir == '': dir = '.'  # HACK, but appears necessary
for fname in os.listdir(dir):
if fname.endswith('.py'):
modtime = os.stat(os.path.join(dir, fname)).st_mtime
if modtime > latest: latest = modtime
out = time.strftime('%Y-%m-%d', time.localtime(latest))
return out

Here's how I'd do it with your specs:
 def lastModDate(directory=None):
"Latest modification ISO date string of .py files in this directory"
import os, time
latest = 0
if directory is None:
directory = os.path.dirname(__file__)
for fname in os.listdir(directory or '.'):
if fname.endswith('.py'):
modtime = os.stat(os.path.join(directory, fname)).st_mtime
if modtime > latest:
latest = modtime
return time.strftime('%Y-%m-%d', time.localtime(latest))

And I'd prefer:
 def lastPyDate(directory=None):
"Latest modification ISO date string of .py files in this file tree"
import os, time
latest = 0
if directory is None:
directory = os.path.dirname(__file__)
for base, dirs, files in os.walk(directory):
for name in files:
if name.endswith('.py'):
modtime = os.stat(os.path.join(base, name)).st_mtime
if modtime > latest:
latest = modtime
return time.strftime('%Y-%m-%d', time.localtime(latest))

But, as someone mentioned, if one of your users edits one of your files
without changing it, he has accidentally changed the version of the
code.  This you could forestall by invoking your function at packaging
time, and writing a file with the version string in it.

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


Re: A java hobbyist programmer learning python

2009-01-19 Thread Rhodri James
On Sun, 18 Jan 2009 02:24:51 -, Steven D'Aprano  
 wrote:



Let me re-write your code in a more Pythonic way. This is not the only
way to do this, and it probably isn't the best way, but it may give you a
flavour for the way Python is usually written.


import sys
import operator



class Calculator():
dispatch = {  # dispatch table mapping symbol to function
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
def __init__(self):
self.operator = sys.argv[1]
self.arg1 = int(sys.argv[2])
self.arg2 = int(sys.argv[3])


If you want the test code to work, I think you mean:

def __init__(self, op, arg1, arg2):
self.operator = op
self.arg1 = arg1
self.arg2 = arg2

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


Re: reading file to list

2009-01-19 Thread Rhodri James

On Sun, 18 Jan 2009 08:31:15 -, Xah Lee  wrote:


On Jan 17, 10:25 am, Tino Wildenhain  wrote:

> [[int(x) for x in line.split()] for line in open("blob.txt")]


Nice (python code).

Few comments:

• the above code is borderline of atypical. e.g. it is not a average
python code would produce or one'd seen in corporate python code.


I can't imagine why not.  It's clean and clear, after all.  If I
needed to do the slightly odd processing that it's written to do,
the only change I'd make for production code is to wrap the file
object in a 'with' statement.


• voodoo like the above makes me dislike python. To me, the one
advantage of python is its clarity enforced by its syntax.
Specifically, the forced indendation and quite simple semantics.
However, the way i've seen Guido's propensities and how python 3 is
moving to, it is becoming more mumbo jumbo of computer sciency OOP
jargons with syntax soup. (with iterators, enumerators, list
comprehension... shits forced upon the users)

The above line illustrate well the ad hoc syntax soup nature python is
moving into.


To a native English speaker, it illustrates entirely the reverse.
List comprehension is actually quite a linguistically natural way
to express the iterative construction of a list.

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


Re: Logging help

2009-01-19 Thread Chris Rebert
On Mon, Jan 19, 2009 at 11:36 AM, koranthala  wrote:
> Hi,
>   Is it possible somehow to have the logging module rotate the files
> every time I start it.
>   Basically, I can automatically rotate using RotatingFileHandler;
> Now I want it rotated every time I start the program too.

Just call the .doRollover() method of the RotatingFileHandler at the
start of the program.
Reading The Fine Documentation for the module is helpful.

Cheers,
Chris

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


Re: defining class functions

2009-01-19 Thread Astan Chee
Actually, yes, I just realized a better way of doing this without state 
change based on the requirement.

Thanks for the info anyway

Nehemiah Dacres wrote:
wouldn't you use a state change? Use a variable to indicate which 
function you want the first class to do


On Mon, Jan 19, 2009 at 6:31 PM, James Mills 
mailto:prolo...@shortcircuit.net.au>> 
wrote:


On Tue, Jan 20, 2009 at 10:08 AM, Astan Chee mailto:astan.c...@al.com.au>> wrote:
> Hi,
> I have two classes in python that are in two different
files/python scripts.
> Class A uses Class B like this:
> class B(object):
>   def function1(self,something):
>   pass
>   def function2(self,something):
>   print "hello one"
>   print something
>
> class A(object):
>   def __init__(self):
> instance = B()
> instance.function2("hello two")
> self.function3()
>   def function3(self):
> print "hello three"

def function3(self):
  print "hello three"
  self.instance.function1 = lambda x; x

But you must bind instnace to self in B

Modify your __init__ as follows:

class A(object):
  def __init__(self):
 self.instance = B()
 self.instance.function2("hello two")
 self.function3()

What's the use-case anyway ?
There might be a better way to solve your problem :)

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




--

"lalalalala! it's not broken because I can use it"

http://linux.slashdot.org/comments.pl?sid=194281&threshold=1&commentsort=0&mode=thread&cid=15927703 

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


Re: defining class functions

2009-01-19 Thread James Stroud

Astan Chee wrote:

Hi,
I have two classes in python that are in two different files/python 
scripts. Class A uses Class B like this:

class B(object):
   def function1(self,something):
   pass
   def function2(self,something):
   print "hello one"
   print something

class A(object):
   def __init__(self):
 instance = B()
 instance.function2("hello two")
 self.function3()
   def function3(self):
 print "hello three"

What I want to do here is to (re)define function1 from function3. Is 
that possible? Is there any way of redefining a function of another 
class without inheriting it? Does this make sense?


I know what you mean, but it doesn't make a lot of sense.

Best practice is to make the function module level, especially if self 
is not referenced beyond the function definition. If self is referenced, 
then all selves must share the same behavior if not the same heredity, 
and using a module level function is still best:


def function(quacker):
  print "hello there"
  quacker.quack()

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


Re: ifconfig in python

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 10:28 AM, Nehemiah Dacres  wrote:
> Is ther an easy way to get the resolved ip address of the machine a script
> is running on? socket.gethostbyname(socket.gethostname) has only returned
> the ip address of my loop back interface ... not very usefull.

That's because your /etc/hosts resolves
your hostname to 127.0.0.1 :)

And no I know of no "easy" way cross
platform way. Perhaps parsing the output
of ifconfig itself ?

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


Re: defining class functions

2009-01-19 Thread Nehemiah Dacres
wouldn't you use a state change? Use a variable to indicate which function
you want the first class to do

On Mon, Jan 19, 2009 at 6:31 PM, James Mills
wrote:

> On Tue, Jan 20, 2009 at 10:08 AM, Astan Chee  wrote:
> > Hi,
> > I have two classes in python that are in two different files/python
> scripts.
> > Class A uses Class B like this:
> > class B(object):
> >   def function1(self,something):
> >   pass
> >   def function2(self,something):
> >   print "hello one"
> >   print something
> >
> > class A(object):
> >   def __init__(self):
> > instance = B()
> > instance.function2("hello two")
> > self.function3()
> >   def function3(self):
> > print "hello three"
>
> def function3(self):
>   print "hello three"
>self.instance.function1 = lambda x; x
>
> But you must bind instnace to self in B
>
> Modify your __init__ as follows:
>
> class A(object):
>   def __init__(self):
>   self.instance = B()
>  self.instance.function2("hello two")
>  self.function3()
>
> What's the use-case anyway ?
> There might be a better way to solve your problem :)
>
> cheers
> James
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 

"lalalalala! it's not broken because I can use it"

http://linux.slashdot.org/comments.pl?sid=194281&threshold=1&commentsort=0&mode=thread&cid=15927703
--
http://mail.python.org/mailman/listinfo/python-list


Re: defining class functions

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 10:08 AM, Astan Chee  wrote:
> Hi,
> I have two classes in python that are in two different files/python scripts.
> Class A uses Class B like this:
> class B(object):
>   def function1(self,something):
>   pass
>   def function2(self,something):
>   print "hello one"
>   print something
>
> class A(object):
>   def __init__(self):
> instance = B()
> instance.function2("hello two")
> self.function3()
>   def function3(self):
> print "hello three"

def function3(self):
   print "hello three"
   self.instance.function1 = lambda x; x

But you must bind instnace to self in B

Modify your __init__ as follows:

class A(object):
   def __init__(self):
  self.instance = B()
  self.instance.function2("hello two")
  self.function3()

What's the use-case anyway ?
There might be a better way to solve your problem :)

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


Re: wsgi silently swallows errors

2009-01-19 Thread Дамјан Георгиевски


> Consider the following wsgi app:
> 
> def application(env, start_response):
>   start_response('200 OK',[('Content-type','text/plain')])
>   yield "hello"
>   x=1/0
>   yield "world"
> 
> The result of this is that the web browser displays "hello" and an
> error
> message ends up in the web log.  But there is no other indication that
> an error has occurred.
> 
> Is there any way to get WSGI to not silently swallow errors that occur
> after start_response has been called?

yes, you can wrap your app in a WebError middleware
http://pypi.python.org/pypi/WebError

from weberror.evalexception import EvalException
application = EvalException(application)


-- 
дамјан ( http://softver.org.mk/damjan/ )

In theory, there is no difference between theory and practice.
 But, in practice, there is.
--
http://mail.python.org/mailman/listinfo/python-list


ifconfig in python

2009-01-19 Thread Nehemiah Dacres
Is ther an easy way to get the resolved ip address of the machine a script
is running on? socket.gethostbyname(socket.gethostname) has only returned
the ip address of my loop back interface ... not very usefull.

-- 

"lalalalala! it's not broken because I can use it"

http://linux.slashdot.org/comments.pl?sid=194281&threshold=1&commentsort=0&mode=thread&cid=15927703
--
http://mail.python.org/mailman/listinfo/python-list


defining class functions

2009-01-19 Thread Astan Chee

Hi,
I have two classes in python that are in two different files/python 
scripts. Class A uses Class B like this:

class B(object):
   def function1(self,something):
   pass
   def function2(self,something):
   print "hello one"
   print something

class A(object):
   def __init__(self):
 instance = B()
 instance.function2("hello two")
 self.function3()
   def function3(self):
 print "hello three"

What I want to do here is to (re)define function1 from function3. Is 
that possible? Is there any way of redefining a function of another 
class without inheriting it? Does this make sense?

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


Re: urllib2 httplib.BadStatusLine exception while opening a page on an Oracle HTTP Server

2009-01-19 Thread Steven D'Aprano
On Mon, 19 Jan 2009 13:00:44 -0800, ak wrote:

> Hi everyone,
> 
> I have a problem with urllib2 on this particular url, hosted on an
> Oracle HTTP Server
> 
> http://www.orange.sk/eshop/sk/portal/catalog.html?
type=post&subtype=phone&null
> 
> which gets 302 redirected to
> https://www.orange.sk/eshop/sk/catalog/post/phones.html, after setting a
> cookie through the Set-Cookie header field in the 302 reply. This works
> fin with firefox.
> 
> However, with urllib2 and the following code snippet, it doesn't work


Looking at the BadStatusLine exception raised, the server response line 
is empty. Looking at the source for httpllib suggests to me that the 
server closed the connection early. Perhaps it doesn't like connections 
from urllib2? 

I ran a test pretending to be IE using this code:

cookiejar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
url = 'http://www.orange.sk/eshop/sk/portal/catalog.html?' \
'type=post&subtype=phone&null'
agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; " \
"NeosBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"
headers = {'User-Agent': agent}
req = urllib2.Request(url, data=None, headers=headers)
try:
s=opener.open(req)
except httplib.BadStatusLine, e:
print e, e.line
else:
print "Success"



but it failed. So the problem is not as simple as changing the user-agent 
string.

Other than that, I'm stumped.



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


Re: function to find the modification date of the project

2009-01-19 Thread Steven D'Aprano
On Mon, 19 Jan 2009 16:19:39 -0700, Joe Strout wrote:

> James Mills wrote:
> 
>> You know you could just store a __version__ attribute in your main
>> library (__init__.py). :)
> 
> What, and update it manually?  I don't trust myself to remember to do
> that every time!

Presumably you have some sort of procedure for releasing software,  
("Does it pass all the unit tests? Website updated? Okay, now ship it!"). 
Perhaps what you need is to add to that procedure a unit test that you 
run before each release (but not during development) which fails if you 
haven't updated the version number.


Also you should consider submitting a feature request for listdir() to 
accept the empty string as equivalent to '.'.



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


Re: function to find the modification date of the project

2009-01-19 Thread Terry Reedy

Joe Strout wrote:

James Mills wrote:


Also I'd like to point out that your method is not
very reliable as the modification time of those
files could change at any moment. Consider
unix systems for instnace where you could do:

touch *

And poof, you're modification times are now
the current time!


Yes, and presumably if some power user did this, then that would be the 
intended effect.  Not sure why they'd do that, but they must have a good 
reason -- who am I to stop them?


What if a curious user simple looks at a file with an editor and saves 
it without change?  Or changes it inconsequentially? Or makes copy to 
x.py.orig, edits and plays with original, and when done renames 
x.py.orig to x.py.  Or any such thing (which I have done in 
Pythonxy/Lib) without any intention of changing version date?


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


Re: function to find the modification date of the project

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 9:20 AM, Joe Strout  wrote:
> Yes, and presumably if some power user did this, then that would be the
> intended effect.  Not sure why they'd do that, but they must have a good
> reason -- who am I to stop them?

Actually I'm fairly certain there -could-
potentially be tools out there that would
inadvertantly do this :) Who knows! :)

Anyway, thanks for sharing your code.
Though I'd take MRAB's suggestion and try
to simplify your function :)

Less is more!

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


Re: function to find the modification date of the project

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 9:19 AM, Joe Strout  wrote:
> James Mills wrote:
>
>> You know you could just store a __version__
>> attribute in your main library (__init__.py). :)
>
> What, and update it manually?  I don't trust myself to remember to do that
> every time!

If you read my post carefully you'll have seen
that I in fact do not update it manually.

It's updated when I do:

$ python setup.py sdist

or bdist or bdist_egg

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


Re: python resource management

2009-01-19 Thread Terry Reedy

S.Selvam Siva wrote:

Hi all,

I am running a python script which parses nearly 22,000 html files 
locally stored using BeautifulSoup.
The problem is the memory usage linearly increases as the files are 
being parsed.
When the script has crossed parsing 200 files or so, it consumes all the 
available RAM and The CPU usage comes down to 0% (may be due to 
excessive paging).


I have to guess that you are somehow holding on to data associated with 
each file.



We tried 'del soup_object'  and used 'gc.collect()'. But, no improvement.


'del ob' only deletes the association between name 'ob' and the object 
it was associated with.  The object itself cannot disappear until all 
associations are gone.


gc.collect only deletes circularly associated objects that collectively 
are isolated.


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


Re: function to find the modification date of the project

2009-01-19 Thread Joe Strout

James Mills wrote:


Also I'd like to point out that your method is not
very reliable as the modification time of those
files could change at any moment. Consider
unix systems for instnace where you could do:

touch *

And poof, you're modification times are now
the current time!


Yes, and presumably if some power user did this, then that would be the 
intended effect.  Not sure why they'd do that, but they must have a good 
reason -- who am I to stop them?


Cheers,
- Joe

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


Re: function to find the modification date of the project

2009-01-19 Thread Joe Strout

James Mills wrote:


You know you could just store a __version__
attribute in your main library (__init__.py). :)


What, and update it manually?  I don't trust myself to remember to do 
that every time!


Best,
- Joe


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


Problem with IDLE on windows XP

2009-01-19 Thread Grimes, George
I am trying to learn Python and I installed version 2.6 both at home and at 
work.  At home, on
Vista, everything works fine.  At work, on XP, IDLE would not run.  I 
uninstalled/reinstalled
and got the same thing.  My cursor changes to the wait symbol for a few 
seconds, then goes
back to normal and ….nothing.  The Task Manager shows nothing.  I uninstalled 
again,
made sure all the files were deleted from the disk, used regedit to delte every 
registry entry
that had python in it and tried version 3.0.

Geuss, what?  I still can’t run IDLE on XP?  Is this a common problem?  Or am I 
unique?

Thanks,
George


George A. Grimes
972-995-0190 - Desk
214-205-0244 - Cell

Failure is the opportunity to begin again, more intelligently.
Henry 
Ford

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


Re: function to find the modification date of the project

2009-01-19 Thread MRAB

Joe Strout wrote:
This isn't a question, but something I thought others may find useful 
(and if somebody can spot any errors with it, I'll be grateful).


We had a case recently where the client was running an older version of 
our app, and didn't realize it.  In other languages I've avoided this by 
displaying the compile date in the About box, but of course Python 
doesn't really have a meaningful compile date.  So, instead we're now 
displaying the latest modification date of any .py file in the project. 
 Here's the function that finds that:



def lastModDate():
"Get the latest modification date (as a string) of any .py file in 
this project."

import os, time
latest = 0
dir = os.path.dirname(__file__)
if dir == '': dir = '.'  # HACK, but appears necessary
for fname in os.listdir(dir):
if fname.endswith('.py'):
modtime = os.stat(os.path.join(dir, fname)).st_mtime
if modtime > latest: latest = modtime
out = time.strftime('%Y-%m-%d', time.localtime(latest))
return out


The intent of this code is to find any .py files in the same directory 
as the module containing the above code, and return (as a date string in 
SQL/ISO format) the latest modification date thereof.  Then, this is 
displayed to the user in the about box like so:


dlg = wx.MessageDialog(self,
  "etown unified database system\nRevision: %s" \
  % lastModDate(),
  "About etown Central", wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()

(That's wxPython, of course.)

I haven't yet tested this in a packaged app or on Windows, but it seems 
to work in our OS X test environment.


One odd thing was the need to employ the HACK identified above, where if 
__file__ happens to already be in the current directory, then 
os.path.dirname of it returns the empty-string -- yet the empty-string 
is not a valid argument to os.listdir().  Is there a better way to a 
list of files in the same directory as a given file?



I tend to prefer:

dir = os.path.dirname(sys.argv[0])

and:

modtime = os.path.getmtime(os.path.join(dir, fname))

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


Re: function to find the modification date of the project

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 8:39 AM, James Mills
 wrote:
> On Tue, Jan 20, 2009 at 7:44 AM, Joe Strout  wrote:
>> This isn't a question, but something I thought others may find useful (and
>> if somebody can spot any errors with it, I'll be grateful).
>>
>> We had a case recently where the client was running an older version of our
>> app, and didn't realize it.  In other languages I've avoided this by
>> displaying the compile date in the About box, but of course Python doesn't
>> really have a meaningful compile date.  So, instead we're now displaying the
>> latest modification date of any .py file in the project.  Here's the
>> function that finds that:
>
> You know you could just store a __version__
> attribute in your main library (__init__.py). :)
>
> Normally in my project, this version string
> is stored in __version__.py in my library and
> fetched in by my library's __init__.py and setup.py
> for distribution. Works great :)

Also I'd like to point out that your method is not
very reliable as the modification time of those
files could change at any moment. Consider
unix systems for instnace where you could do:

touch *

And poof, you're modification times are now
the current time!

Sorry for finding flaws in your approach! :)

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


Re: function to find the modification date of the project

2009-01-19 Thread James Mills
On Tue, Jan 20, 2009 at 7:44 AM, Joe Strout  wrote:
> This isn't a question, but something I thought others may find useful (and
> if somebody can spot any errors with it, I'll be grateful).
>
> We had a case recently where the client was running an older version of our
> app, and didn't realize it.  In other languages I've avoided this by
> displaying the compile date in the About box, but of course Python doesn't
> really have a meaningful compile date.  So, instead we're now displaying the
> latest modification date of any .py file in the project.  Here's the
> function that finds that:

You know you could just store a __version__
attribute in your main library (__init__.py). :)

Normally in my project, this version string
is stored in __version__.py in my library and
fetched in by my library's __init__.py and setup.py
for distribution. Works great :)

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


Re: tasklet library based on PEP 0342

2009-01-19 Thread Terry Reedy

charlie...@gmail.com wrote:


Using new features of python generators, as described in PEP 0342, it
is possible to write some sort of "tasklets" in a maner very similar
to stackless python, but running on cpython. For example :

@tasklet
def my_task():
yield Timer(10)
yield "result"

@tasklet
def other_task():
result = yield my_task()

other_task().start(callback=on_return)


I wrote an implementation of this in the scope of an open source
project for openmoko [0], there is also an other very similar
implementation from the kiwi project [1].

This kind of tool is very useful, but unfortunately there is no
standard library that would provide a unified way to use it
independently of the underlying event loop.

Does someone know if a similar library could eventually be added into
python standard libraries ? Would it be accepted as a PEP ?


Start by listing your module/library on http://pypi.python.org/pypi
To ever get in the stdlib, it must be tested, used by several different 
people, the best of its type, and relative stable.


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


function to find the modification date of the project

2009-01-19 Thread Joe Strout
This isn't a question, but something I thought others may find useful 
(and if somebody can spot any errors with it, I'll be grateful).


We had a case recently where the client was running an older version of 
our app, and didn't realize it.  In other languages I've avoided this by 
displaying the compile date in the About box, but of course Python 
doesn't really have a meaningful compile date.  So, instead we're now 
displaying the latest modification date of any .py file in the project. 
 Here's the function that finds that:



def lastModDate():
"Get the latest modification date (as a string) of any .py file in 
this project."

import os, time
latest = 0
dir = os.path.dirname(__file__)
if dir == '': dir = '.'  # HACK, but appears necessary
for fname in os.listdir(dir):
if fname.endswith('.py'):
modtime = os.stat(os.path.join(dir, fname)).st_mtime
if modtime > latest: latest = modtime
out = time.strftime('%Y-%m-%d', time.localtime(latest))
return out


The intent of this code is to find any .py files in the same directory 
as the module containing the above code, and return (as a date string in 
SQL/ISO format) the latest modification date thereof.  Then, this is 
displayed to the user in the about box like so:


dlg = wx.MessageDialog(self,
  "etown unified database system\nRevision: %s" \
  % lastModDate(),
  "About etown Central", wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()

(That's wxPython, of course.)

I haven't yet tested this in a packaged app or on Windows, but it seems 
to work in our OS X test environment.


One odd thing was the need to employ the HACK identified above, where if 
__file__ happens to already be in the current directory, then 
os.path.dirname of it returns the empty-string -- yet the empty-string 
is not a valid argument to os.listdir().  Is there a better way to a 
list of files in the same directory as a given file?


Cheers,
- Joe

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


Re: Ordering attributes for dynamically generated class

2009-01-19 Thread David Pratt

Hi Aaron, this worked out fine. Using an ordered dict to subclass dict.

Many thanks.
David

On Jan 18, 2009, at 11:57 AM, Aaron Brady wrote:


On Jan 18, 9:52 am, David Pratt  wrote:

Hi list. I use 'type' to generate classes but have a need to order
the attributes for the generated class. Of course a dict is not going
to maintain ordering. Is there any way to dynamically generate a
class with attributes in specific order?

my_new_class = type( 'MyNewClass', tuple_of_bases,  
dict_of_attributes)


Many thanks,
David


Just a thought, you can subclass 'dict' and assign an instance of it
to the __dict__ member of your new instance.
--
http://mail.python.org/mailman/listinfo/python-list


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


Re: Beginner Question

2009-01-19 Thread Terry Reedy

K-Dawg wrote:


I do no understand the underscore methods.


Names of the form __xyx__ are defined by the language definition and 
recognized and used by the interpreter.


See PythonLanguage / LexicalAnalysis / Identifiers / Reserved

Most refer to methods, a few to other attributes.  Modules may have 
several non-method attributes, such as '__builtins__', '__doc__', 
'__file__', '__name__', and '__package__'.


The top-level module created when the interpreter starts is given the 
name '__main__'.  If a module is imported, it __name__ is the import name.


>>> __name__
'__main__'
>>> import email
>>> email.__name__
'email'
>>> email.__file__
'C:\\Programs\\Python30\\lib\\email\\__init__.py'

If email were run directly, its name would be __main__ while the 
__file__ would be the same.


Most syntax operations have a corresponding special that implements the 
operation.  This allows user-defined objects to fully participate in 
syntax operations on an equal basis with built-in objects.


See PythonLanguage Manual / Data model / Special operations.

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


Re: wsgi silently swallows errors

2009-01-19 Thread Graham Dumpleton
On Jan 20, 8:03 am, Jean-Paul Calderone  wrote:
> On Mon, 19 Jan 2009 12:15:29 -0800, Ron Garret  wrote:
> >Consider the following wsgi app:
>
> >def application(env, start_response):
> >  start_response('200 OK',[('Content-type','text/plain')])
> >  yield "hello"
> >  x=1/0
> >  yield "world"
>
> >The result of this is that the web browser displays "hello" and an error
> >message ends up in the web log.  But there is no other indication that
> >an error has occurred.
>
> >Is there any way to get WSGI to not silently swallow errors that occur
> >after start_response has been called?
>
> WSGI is a specification, not a piece of software.  The specification isn't
> swallowing the error, some piece of software is.  What WSGI container are
> you using?

Not Apache/mod_wsgi at least, as message would show in Apache error
logs.

[Tue Jan 20 09:03:19 2009] [info] [client ::1] mod_wsgi (pid=271,
process='wsgi', application='dangermouse:8224|/wsgi/scripts/
swallow.py'): Loading WSGI script '/usr/local/wsgi/scripts/swallow.py'
[Tue Jan 20 09:03:19 2009] [error] [client ::1] mod_wsgi (pid=271):
Exception occurred processing WSGI script '/usr/local/wsgi/scripts/
swallow.py'
[Tue Jan 20 09:03:19 2009] [error] [client ::1] Traceback (most recent
call last)
[Tue Jan 20 09:03:19 2009] [error] [client ::1]   File "/usr/local/
wsgi/scripts/swallow.py", line 7, in application[Tue Jan 20 09:03:19
2009] [error] [client ::1] x=1/0
[Tue Jan 20 09:03:19 2009] [error] [client ::1] ZeroDivisionError:
integer division or modulo by zero

Would just need to make sure you look in the correct log if have
virtual host specific error logs.

Graham

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


Re: string formatting documentation

2009-01-19 Thread Terry Reedy

Alan G Isaac wrote:

On Mon, 19 Jan 2009 14:44:01 +, Alan G Isaac wrote:
we are supposed to prefer 


No, no 'supposed to's.  You are not even 'supposed to' like or use 
Python.  (Unless, I supposed, an employer demands it.  But that is 
another story.)  Certainly, one is not 'supposed to' prefer the new to 
the carefully picked best use example of the old.  Guido and some 
developers prefer the totality of uses cases and possibilities of 
.format to the same for % formatting.



On 1/19/2009 10:01 AM Steven D'Aprano apparently wrote:
Well, that second example certainly is a WTF. I think we are supposed 
to prefer:



'{0}{0}'.format('wtf?')
to '%%s%s' % 'wtf?' % 'wtf?'


But your replacement misses the point of the example,


I read it the same way and has the same thought as Steven.
Perhaps all the obviously angry 'wtf?'s distracted me.


which is that sequential formatting is often needed.
That is, you need to generate a format string from
a format string.  More explicitly:

'{{0}} {0}'.format('earlyinfo').format('lateinfo')

'%%s %s' % 'earlyinfo' % 'lateinfo'


This is what you should have written.  Having never seen or done this, I 
 first missed the doubled '%%' and read it as a syntax error.



I would like assurance that it is not deprecated.
Can you back that?


If you claim something exists, you have the burden of proof.
I have not seen 3.0 emit a % deprecation warning.  Have you?

Last I read, Guido *plans* to deprecate % formatting 'sometime'.

Terry Jan Reedy

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


Re: urllib2 httplib.BadStatusLine exception while opening a page on an Oracle HTTP Server

2009-01-19 Thread ak
On Jan 19, 10:00 pm, ak  wrote:
> Hi everyone,
>
> I have a problem with urllib2 on this particular url, hosted on an
> Oracle HTTP Server
>
> http://www.orange.sk/eshop/sk/portal/catalog.html?type=post&subtype=p...
>
> which gets 302 redirected 
> tohttps://www.orange.sk/eshop/sk/catalog/post/phones.html,
> after setting a cookie through the Set-Cookie header field in the 302
> reply. This works fin with firefox.
>
> However, with urllib2 and the following code snippet, it doesn't work
>
> 
> import cookiejar
> import urllib2
>
> cookiejar = cookielib.LWPCookieJar()
> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
> url = 'http://www.orange.sk/eshop/sk/portal/catalog.html?
> type=post&subtype=phone&null'
> req = urllib2.Request(url, None)
> s=opener.open(req)
> 
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/urllib2.py", line 387, in open
>     response = meth(req, response)
>   File "/usr/lib/python2.5/urllib2.py", line 498, in http_response
>     'http', request, response, code, msg, hdrs)
>   File "/usr/lib/python2.5/urllib2.py", line 419, in error
>     result = self._call_chain(*args)
>   File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain
>     result = func(*args)
>   File "/usr/lib/python2.5/urllib2.py", line 582, in http_error_302
>     return self.parent.open(new)
>   File "/usr/lib/python2.5/urllib2.py", line 381, in open
>     response = self._open(req, data)
>   File "/usr/lib/python2.5/urllib2.py", line 399, in _open
>     '_open', req)
>   File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain
>     result = func(*args)
>   File "/usr/lib/python2.5/urllib2.py", line 1115, in https_open
>     return self.do_open(httplib.HTTPSConnection, req)
>   File "/usr/lib/python2.5/urllib2.py", line 1080, in do_open
>     r = h.getresponse()
>   File "/usr/lib/python2.5/httplib.py", line 928, in getresponse
>     response.begin()
>   File "/usr/lib/python2.5/httplib.py", line 385, in begin
>     version, status, reason = self._read_status()
>   File "/usr/lib/python2.5/httplib.py", line 349, in _read_status
>     raise BadStatusLine(line)
> httplib.BadStatusLine
>
> Trying the redirected url directly doesn't work either (trying with
> Firefox will give an HTML error page, as the cookie is not set yet,
> but trying with urllib2 gives the same exception as previously,
> whereas it should return the HTML error page)
> This works correctly on other urls on this website (http(s)://www.orange.sk).
>
> Am I doing anything wrong or is this a bug in urllib2 ?
>
> -- ak


Actually, I was wrong on the last point, this does *not* work on
https://www.orange.sk (but does on http://www.orange.sk). IMHO, this
means either urllib2 or the server misimplemented HTTPS.

Here's some output with debuglevel=1 :

>>> opener.open(urllib2.Request('http://www.orange.sk/', None, headers))
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Mon, 19 Jan 2009 21:44:03 GMT
header: Server: Oracle-Application-Server-10g/10.1.3.1.0 Oracle-HTTP-
Server
header: Set-Cookie:
JSESSIONID=0a19055a30d630c427bda71d4e26a37ca604b9f590dc.e3eNaNiRah4Pe3aSch8Sc3yOc40;
path=/web
header: Expires: Mon, 19 Jan 2009 21:44:13 GMT
header: Surrogate-Control: max-age="10"
header: Content-Type: text/html; charset=ISO-8859-2
header: X-Cache: MISS from www.orange.sk
header: Connection: close
header: Transfer-Encoding: chunked
>

>>> opener.open(urllib2.Request('https://www.orange.sk/', None, headers))
reply: ''
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/urllib2.py", line 381, in open
response = self._open(req, data)
  File "/usr/lib/python2.5/urllib2.py", line 399, in _open
'_open', req)
  File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain
result = func(*args)
  File "/usr/lib/python2.5/urllib2.py", line 1115, in https_open
return self.do_open(httplib.HTTPSConnection, req)
  File "/usr/lib/python2.5/urllib2.py", line 1080, in do_open
r = h.getresponse()
  File "/usr/lib/python2.5/httplib.py", line 928, in getresponse
response.begin()
  File "/usr/lib/python2.5/httplib.py", line 385, in begin
version, status, reason = self._read_status()
  File "/usr/lib/python2.5/httplib.py", line 349, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine

As you can see the reply from the server seems empty (which results in
the BadStatusLine exception)

Any help greatly appreciated.

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


Re: PyQt4 on Windows ?

2009-01-19 Thread Stephen Chapman
I have one running.  actually use freezer to create an exe for it in 
windows. 
http://www.riverbankcomputing.co.uk/software/pyqt/download
That will tell you how to get started. 
The app I wrote uses Pryro(with middleware server on a linux machine).  
And I use the standard widgets

that qt has grid, table , combobox etc


Linuxguy123 wrote:

What does it take to get a PyQt4 application running on a Windows
machine ?

I'm sorry if this is a redundant question, but I've searched this and I
am not finding a comprehensive answer.

If anyone is running a PyQt4 application on a Windows (XP or Vista)
machine, I'd love to know how it works for you and how extensive the
application is and how much of the Qt library it uses.

Thanks

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


  


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


Re: string formatting documentation

2009-01-19 Thread Steven D'Aprano
On Mon, 19 Jan 2009 15:38:02 +, Alan G Isaac wrote:

> But of more interest: you claim PEP 4 is not relevant, and that old
> string formatting is NOT deprecated. I would like assurance that it is
> not deprecated. Can you back that?

If you want to know what python-dev have in mind, you have to ask them, 
not me.

But as I see it, the earliest % formatting could be removed would be 
Python 3.2: Python 3.1 to get a formal deprecation warning, with 
removal no earlier than 3.2. So you've got about a year to change their 
mind about deprecating the old style, or alternatively, a year to get 
used to the new style, followed by another year for % to go away 
completely.




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


PyQt4 on Windows ?

2009-01-19 Thread Linuxguy123
What does it take to get a PyQt4 application running on a Windows
machine ?

I'm sorry if this is a redundant question, but I've searched this and I
am not finding a comprehensive answer.

If anyone is running a PyQt4 application on a Windows (XP or Vista)
machine, I'd love to know how it works for you and how extensive the
application is and how much of the Qt library it uses.

Thanks

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


Re: Python Style Guide Questions - Contd.

2009-01-19 Thread Marc 'BlackJack' Rintsch
On Mon, 19 Jan 2009 05:50:54 -0800, koranthala wrote:

> Hi,
>I have some more questions about python code styling. 1. Global
>Variables: In my code, I am using some global variables.
> Now, when I ran PyLint, it raised convention errors mentioning that they
> should be CAPITAL_ALPHABETS. Now, in PEP 8, I did not see that
> mentioned. Please let me know whether that is the usual styling
> mechanism which is used.

PEP8 doesn't mention constants at all.  The all caps naming for constants 
is a convention in several languages.

>2. I have many loops wherein I define a variable as just a counter.
>for x in range(counter):
>   do_something()
>Please note that I am not using x anywhere in the program. Pylint
>again raises warnings saying that the variable should be
> used.
>Should I disregard it or use the default variable _ ? for _ in
>range(counter):
>   do_something()
>pylint does not raise errors for those. Are there any issues in
> using _ ?

Pylint doesn't barf on `dummy` either.  The point is having a name that 
makes clear at the head of the loop, that the reader doesn't have to 
bother looking for places where the value will be used because it is 
clear from the name that the value won't be used at all.

BTW pylint is very configurable, you can dump the default configuration 
and find out which names are "allowed" by default and of course define 
your own set of "value doesn't matter" names.

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


Re: Regular expression that skips single line comments?

2009-01-19 Thread Steven D'Aprano
On Mon, 19 Jan 2009 08:08:01 -0800, martinjamesevans wrote:

> I am trying to parse a set of files that have a simple syntax using RE.
> I'm interested in counting '$' expansions in the files, with one minor
> consideration. A line becomes a comment if the first non-white space
> character is a semicolon.

Since your data is line-based, surely the simplest, clearest and most 
natural solution is to parse each line individually instead of trying to 
process the entire input with a single RE?


def extract_dollar_expansions(sInput):
accumulator = []
for line in sInput.split('\n'):
line = line.lstrip()
if line.startswith(';'):
continue
accumulator.extend(re.findall(r"(\$.)", line))
return accumulator


(Aside: why are you doing a case-insensitive match for a non-letter? Are 
there different upper- and lower-case dollar signs?)



>>> extract_dollar_expansions(sInput)
['$3', '$3', '$3', '$5', '$6', '$7']




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


urllib2 httplib.BadStatusLine exception while opening a page on an Oracle HTTP Server

2009-01-19 Thread ak
Hi everyone,

I have a problem with urllib2 on this particular url, hosted on an
Oracle HTTP Server

http://www.orange.sk/eshop/sk/portal/catalog.html?type=post&subtype=phone&null

which gets 302 redirected to 
https://www.orange.sk/eshop/sk/catalog/post/phones.html,
after setting a cookie through the Set-Cookie header field in the 302
reply. This works fin with firefox.

However, with urllib2 and the following code snippet, it doesn't work



import cookiejar
import urllib2

cookiejar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
url = 'http://www.orange.sk/eshop/sk/portal/catalog.html?
type=post&subtype=phone&null'
req = urllib2.Request(url, None)
s=opener.open(req)


Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/urllib2.py", line 387, in open
response = meth(req, response)
  File "/usr/lib/python2.5/urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.5/urllib2.py", line 419, in error
result = self._call_chain(*args)
  File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain
result = func(*args)
  File "/usr/lib/python2.5/urllib2.py", line 582, in http_error_302
return self.parent.open(new)
  File "/usr/lib/python2.5/urllib2.py", line 381, in open
response = self._open(req, data)
  File "/usr/lib/python2.5/urllib2.py", line 399, in _open
'_open', req)
  File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain
result = func(*args)
  File "/usr/lib/python2.5/urllib2.py", line 1115, in https_open
return self.do_open(httplib.HTTPSConnection, req)
  File "/usr/lib/python2.5/urllib2.py", line 1080, in do_open
r = h.getresponse()
  File "/usr/lib/python2.5/httplib.py", line 928, in getresponse
response.begin()
  File "/usr/lib/python2.5/httplib.py", line 385, in begin
version, status, reason = self._read_status()
  File "/usr/lib/python2.5/httplib.py", line 349, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine

Trying the redirected url directly doesn't work either (trying with
Firefox will give an HTML error page, as the cookie is not set yet,
but trying with urllib2 gives the same exception as previously,
whereas it should return the HTML error page)
This works correctly on other urls on this website (http(s)://
www.orange.sk).

Am I doing anything wrong or is this a bug in urllib2 ?

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


  1   2   >