Re: Attack a sacred Python Cow

2008-07-27 Thread Carl Banks
On Jul 27, 5:14 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 26 Jul 2008 15:58:16 -0700, Carl Banks wrote:
> > On Jul 26, 5:07 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> >> Whether or not one should write 'if x' or 'if x != 0' [typo corrected]
> >> depends on whether one means the general 'if x is any non-null object
> >> for which bool(x) == True' or the specific 'if x is anything other than
> >> numeric zero'.  The two are not equivalent.  Ditto for the length
> >> example.
>
> > Can you think of any use cases for the former?  And I mean something
> > where it can't be boiled down to a simple explicit test for the sorts of
> > arguments you're expecting; something that really takes advantage of the
> > "all objects are either true or false" paradigm.
>
> But why do you need the explicit test?

I asked you first, buddy.


[snip attempt to reverse argument]
> > The best thing I can come up with out of my mind is cases where you want
> > to check for zero or an empty sequence, and you want to accept None as
> > an alternative negative as well.  But that's pretty weak.
>
> You might find it pretty weak, but I find it a wonderful, powerful
> feature.

Powerful?  You've got to be kidding me.  If I have a function

create_object(name)

where one creates an anonymous object by passing an empty string,
behold! now I can also create an anonymous object by passing None.
You call that powerful?  I call it simple convenience, and not
something that we'd suffer much for for not having.  But it's still
the one thing I can think of that can't be replaced by a simple
explicit test.


> I recently wrote a method that sequentially calls one function after
> another with the same argument, looking for the first function that
> claims a match by returning a non-false result. It looked something like
> this:
>
> def match(arg, *functions):
> for func in functions:
> if func(arg):
> return func
>
> I wanted the function itself, not the result of calling the function. I
> didn't care what the result was, only that it was something (indicates a
> match) or nothing (no match). In one application, the functions might
> return integers or floats; in another they might return strings. In a
> third, they might return re match objects or None. I don't need to care,
> because my code doesn't make any assumptions about the type of the result.

Couldn't you write the function to return None on no match, then test
if func(arg) is None?  That way would seem a lot more natural to me.
As an added bonus, you don't have to return some sort of wrapped
object if suddenly you decide that you want to match a zero.

Sorry, can't give it credit for the use case I was asking for.  I want
something where "if x" will do but a simple explicit test won't.


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


Re: Attack a sacred Python Cow

2008-07-27 Thread s0suk3
On Jul 27, 10:55 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>,
>
>
>
> [EMAIL PROTECTED] wrote:
> > On Jul 26, 6:47 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
> > central.gen.new_zealand> wrote:
> >> In message
> >> <[EMAIL PROTECTED]>,
>
> >> [EMAIL PROTECTED] wrote:
> >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
> >> > central.gen.new_zealand> wrote:
>
> >> >> In message
> >> >> <[EMAIL PROTECTED]>,
> >> >> Jordan wrote:
>
> >> >> > Except when it comes to Classes. I added some classes to code that
> >> >> > had previously just been functions, and you know what I did - or
> >> >> > rather, forgot to do? Put in the 'self'. In front of some of the
> >> >> > variable accesses, but more noticably, at the start of *every single
> >> >> > method argument list.*
>
> >> >> The reason is quite simple. Python is not truly an "object-oriented"
> >> >> language. It's sufficiently close to fool those accustomed to OO ways
> >> >> of doing things, but it doesn't force you to do things that way. You
> >> >> still have the choice. An implicit "self" would take away that choice.
>
> >> > By that logic, C++ is not OO.
>
> >> Yes it is, because it has "this".
>
> > You mean the keyword "this"? It's just a feature. How does that make a
> > difference on being or not being OO?
>
> Because it was one of the things the OP was complaining about (see above).

Wrong. What the OP complains about has no relevance on what makes a
language OO or not.

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 10:32 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Derek Martin wrote:
> > Furthermore, as you described, defining the function within the scope
> > of a class binds a name to the function and then makes it a method of
> > the class.  Once that happens, *the function has become a method*.
>
> If you mean that a user-defined function object becomes a different
> class of object when bound to a class attribute name, that is wrong.
> Once a function, always a function.  It may be called an 'instance
> method' but it is still a function.  Any function object can be an
> attribute of multiple classes, without inheritance, or of none.
>
> When a function attribute is accessed via an instance of the class, it
> is *wrapped* with a bound method object that basically consists of
> references to the function and instance.  When the 'bound method' is
> called, the instance is inserted in front of the other arguments to be
> matched with the first parameter.
>
> In 2.0, functions accessed through the class were rather uselessly
> wrapped as an 'unbound method', but those wrappers have been discarded
> in 3.0.
>
> > To be perfectly honest, the idea that an object method can be defined
> > outside the scope of an object (i.e. where the code has no reason to
> > have any knowledge of the object) seems kind of gross to me...
>
> I happen to like the simplicity that "def statements (and lambda
> expressions) create function objects."  Period.
>
> ...
>
> > It does indeed -- it does more than imply.  It states outright that
> > the function is defined within the namespace of that object,
>
> True.
>
> > and as such that it is inherently part of that object.
>
> False.  That does not follow.  Python objects generally exist
> independently of each other.  Think of them as existing in a nameless
> dataspace if you want.  Collection/container objects collect/contain
> references to their members, just as a club roster does, but they only
> metaphorically 'contain' their members.  Any object can be a member of
> any number of collections, just as humans can join any number of clubs
> and groups.  In mathematical set theory, membership is also non-exclusive.
>
> > So why should it need
> > to be explicitly told about the object of which it is already a part?
>
> Because it is not a 'part' of a class in the sense you seem to mean.
>
> What is true is that functions have a read-only reference to the global
> namespace of the module in which they are defined.  But they do not have
> to be a member of that namespace.
>
> Terry Jan Reedy

This whole discussion reminds me of discussions I saw on comp.lang.ada
several years ago when I had a passing interest in Ada.

My memory on this is a bit fuzzy, but IFIRC Ada 95 did not support
standard OO "dot" syntax of the form

myObject.myFunction(args)

Instead, "myfunction" was just a "regular" function that took
"myObject" and "args" as arguments. It was called as

myFunction(myObject, args)

It was put into the appropriate package or subpackage where it
belonged rather than in a class definition. Namespaces were defined by
a package hierarchy rather than by classes (which is actually more
logical, but that's another topic).

Well, so many people demanded the "dot" notation that it was finally
implemented in Ada 2005. So now user can use the more familiar dot
notation, but my understanding is that it is just "syntactic sugar"
for the old notation.

So when Python people go out of their way to point out that class
"methods" in Python are implemented as regular functions, that seems
fairly obvious to me -- but perhaps only because of my passing
familiarity with Ada.
--
http://mail.python.org/mailman/listinfo/python-list


Re: write unsigned integer 32 bits to socket

2008-07-27 Thread Michael Torrie
[EMAIL PROTECTED] wrote:
> thanks a lot!!! re-read it again!!!
> 
> from the struct doc!
> Standard size and alignment are as follows: no alignment is required
> for any type (so you have to use pad bytes); short is 2 bytes; int and
> long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and
> double are 32-bit and 64-bit IEEE floating point numbers,
> respectively.

Of course any time you send coherent numbers over the network, I highly
recommend you use what's called network byte order.  In C, you'd use the
 htonl() call, and then when pulling it off the wire on the other end
you'd use ntohl().  If you don't then you will have problems when the
endianness is different between the hosts.  Standard convention (even in
the MS word) is to use big-ending across the network.  I'm sure python
has some convention in the struct module for dealing with this.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Michael Torrie
Colin J. Williams wrote:
>>
>> def fun( ., cat):
>>
> I don't see the need for the comma in fun.

It (the entire first variable!) is needed because a method object is
constructed from a normal function object:

def method(self,a,b):
pass

class MyClass(object):
pass

MyClass.testmethod=method

That's precisely the same as if you'd defined method inside of the class
to begin with.  A function becomes a method when the lookup procedure in
the instance object looks up the attribute and returns (from what I
understand) essentially a closure that binds the instance to the first
variable of the function.  The result is known as a bound method, which
is a callable object:

>>> instance=MyClass()

>>> instance.testmethod
>


How would this work if there was not first parameter at all?

In short, unlike what most of the implicit self advocates are saying,
it's not just a simple change to the python parser to do this.  It would
require a change in the interpreter itself and how it deals with classes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Terry Reedy

Derek Martin wrote:


Furthermore, as you described, defining the function within the scope
of a class binds a name to the function and then makes it a method of
the class.  Once that happens, *the function has become a method*.


If you mean that a user-defined function object becomes a different 
class of object when bound to a class attribute name, that is wrong. 
Once a function, always a function.  It may be called an 'instance 
method' but it is still a function.  Any function object can be an 
attribute of multiple classes, without inheritance, or of none.


When a function attribute is accessed via an instance of the class, it 
is *wrapped* with a bound method object that basically consists of 
references to the function and instance.  When the 'bound method' is 
called, the instance is inserted in front of the other arguments to be 
matched with the first parameter.


In 2.0, functions accessed through the class were rather uselessly 
wrapped as an 'unbound method', but those wrappers have been discarded 
in 3.0.



To be perfectly honest, the idea that an object method can be defined
outside the scope of an object (i.e. where the code has no reason to
have any knowledge of the object) seems kind of gross to me...


I happen to like the simplicity that "def statements (and lambda 
expressions) create function objects."  Period.


...

It does indeed -- it does more than imply.  It states outright that
the function is defined within the namespace of that object,


True.


and as such that it is inherently part of that object.


False.  That does not follow.  Python objects generally exist 
independently of each other.  Think of them as existing in a nameless 
dataspace if you want.  Collection/container objects collect/contain 
references to their members, just as a club roster does, but they only 
metaphorically 'contain' their members.  Any object can be a member of 
any number of collections, just as humans can join any number of clubs 
and groups.  In mathematical set theory, membership is also non-exclusive.



So why should it need
to be explicitly told about the object of which it is already a part?


Because it is not a 'part' of a class in the sense you seem to mean.

What is true is that functions have a read-only reference to the global 
namespace of the module in which they are defined.  But they do not have 
to be a member of that namespace.


Terry Jan Reedy

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Michael Torrie
Derek Martin wrote:
> Regardless of how it's implementd, it's such a common idiom to use
> self to refer to object instances within a class in Python that it
> ought to be more automatic.  Personally, I kind of like the idea of
> using @ and thinking of it more like an operator...  Kind of like
> dereferencing a pointer, only with an implied pointer name.
> 
> class foo:
>   def __init__():
>   @.increment = 2
> 
>   def bar(a)
>   return a + @.increment
> 
> I'm sure all the Pythonistas will hate this idea though... ;-)  To be
> honest, it smacks a little of Perl's magic variables, which I actually
> hate with a passion.  This is the only place in Python I'd consider
> doing something like this.  

I think the biggest reason why an implicit self is bad is because it
prevents monkey-patching of existing class objects.  Right now I can add
a new method to any existing class just with a simple attribute like so
(adding a new function to an existing instance object isn't so simple,
but ah well):

def a(self, x, y):
self.x = x
self.y = y

class Test(object):
pass

Test.setxy = a

b = Test()

b.setxy(4,4)

print b.x, b.y

If self was implicit, none of this would work. Now this contrived
example is not useful, and maybe not even correct, but I have patched
existing classes on several occasions using this method.  How could
python retain it's dynamic nature and still have an implicit self?  How
would the interpreter know when to add the self variable and when not to?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 9:44 pm, alex23 <[EMAIL PROTECTED]> wrote:
> > > > > On Jul 27, 4:26 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
> > > > > > Terry Reedy <[EMAIL PROTECTED]> wrote:
> > > > > > > The use of '.' has been suggested before and rejected.
> > > > > > Where and why?
> > Dude, I agree with Guido completely on this one. You
> > seem to be clueless about the issue here. You're the
> > one with the reading comprehension problem. Please
> > quit wasting my time with your irrelevant crap.
>
> I pointed you at a thread -where it had been suggested and rejected-.
> And I'm the clueless one?
>
> I don't think I'm the one wasting anyone's time here, but fine. I've
> got far better things to do with my time than waste it talking to you.

What was "suggested in rejected" on the thread you pointed me to was
not what I suggested. Not even close. Get it, genius?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to figure out if the platform is 32bit or 64bit?

2008-07-27 Thread Manuel Vazquez Acosta
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Just test for maxint value:

from sys import maxint
if maxint >> 33:
print "more than 32 bits" # probably 64
else:
print "32 bits"


Best regards,
Manuel.

Trent Mick wrote:
> norseman wrote:
>>
>>  > > I need to know if I'm running on 32bit or 64bit ... so far I haven't
>>  > > come up with how to get this info via python. sys.platform returns
>>  > > what python was built on ... but not what the current system is.
>>  > >
>>  > > I thought platform.uname() or just platform.processor() would have
>>  > > done it, but python returns an empty string on windows. Any ideas?
> 
> If just for Windows I believe you can use the "PROCESSOR_ARCHITECTURE"
> environment variable -- at least on NT-based Windows versions.
> 
> Values are x86 (32-bit), IA64 (64-bit) and AMD64 (64-bit).
> 
> Here is a "platinfo.py" module that might help if you need to do this
> for other platforms:
> 
> http://svn.openkomodo.com/openkomodo/view/openkomodo/trunk/util/platinfo.py
> 
> 
> Cheers,
> Trent
> 

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkiNU6IACgkQI2zpkmcEAhi6sACgo1ZyGKCWtnBPLXr1EjgSq3V4
GEAAoL+zZStfGYaZxg/zYoUqk6UFa+oM
=g+tz
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread alex23
> > > > On Jul 27, 4:26 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
> > > > > Terry Reedy <[EMAIL PROTECTED]> wrote:
> > > > > > The use of '.' has been suggested before and rejected.
> > > > > Where and why?
> Dude, I agree with Guido completely on this one. You
> seem to be clueless about the issue here. You're the
> one with the reading comprehension problem. Please
> quit wasting my time with your irrelevant crap.

I pointed you at a thread -where it had been suggested and rejected-.
And I'm the clueless one?

I don't think I'm the one wasting anyone's time here, but fine. I've
got far better things to do with my time than waste it talking to you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 8:58 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Jul 27, 2:39 pm, Bruno Desthuilliers
>
> <[EMAIL PROTECTED]> wrote:
> > Derek Martin a écrit :
> > > It's bad programming, but the world is full of bad programmers, and we
> > > don't always have the choice not to use their code.  Isn't one of
> > > Python's goals to minimize opportunities for bad programming?
>
> > Nope. That's Java's goal. Python's goals are to maximize opportunities
> > for good programming, which is quite different.

Oh, gosh, that is so clever. What a bunch of crap.

> +1 QOTW

Do you realize what an insult that is to everyone else who has posted
here in the past week?


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


Re: Command line arguements

2008-07-27 Thread Henry Chang
try optparse  :)
http://docs.python.org/lib/module-optparse.html

On Sun, Jul 27, 2008 at 9:13 PM, aditya shukla
<[EMAIL PROTECTED]>wrote:

> Hello folks ,I have a program in which a text file is generated as an
> output
> eg
>
> C:\prog\ prog -x test.txt
> Right now whenever i have to read the test file i have to put its name
> manually in my code.
> eg
> f=open("c:\\prog\\test.txt","r")
>
> How ever i want to add the name of the test file dynamically to my program
> ie , if every time i give
>
> C:\prog\ prog -x test.txt
> The filename (test.txt) automatically comes in
> f=open("c:\\prog\\test.txt","r")
>
> C:\prog\ prog -x file1.txt
> f=open("c:\\prog\\file1","r")
>
>
> in other words i do not want to do hard code the name of the file in my
> code every time i need to read it.
>
> I was reading about the sys module and i guess sys.argv would take the
> input from the command line whenever i run the python script .
>
> Please guide me in the right direction on how to tackle the problem.
>
> Thanks in advance
>
> Aditya
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 8:38 pm, alex23 <[EMAIL PROTECTED]> wrote:
> On Jul 28, 4:59 am, "Russ P." <[EMAIL PROTECTED]> wrote:
>
> > On Jul 27, 3:11 am, alex23 <[EMAIL PROTECTED]> wrote:
>
> > > On Jul 27, 4:26 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
>
> > > > On Jul 26, 11:18 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> > > > > The use of '.' has been suggested before and rejected.
>
> > > > Where and why?
>
> > > Google is your 
> > > friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html
>
> > What Guido rejected there is most certainly *not*
> > what I suggested. I agree with Guido on that one.
>
> Orly?
>
> Ian Bicking wrote: "I propose that the self argument be removed from
>
> method definitions."
>
> Philip Eby suggested:
>
> >  def .aMethod(arg1, arg2):
> >  return .otherMethod(arg1*2+arg2)
>
> Guido shot them all down by stating:
>
> > [Y]ou're proposing to hide a
> > fundamental truth in Python, that methods are "just" functions whose
> > first argument can be supplied using syntactic sugar
>
> Any more reading comprehension we can do for you?

Dude, I agree with Guido completely on this one. You
seem to be clueless about the issue here. You're the
one with the reading comprehension problem. Please
quit wasting my time with your irrelevant crap.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the correct round() method?

2008-07-27 Thread Gary Herron

josh logan wrote:

On Jul 27, 8:45 pm, pigmartian <[EMAIL PROTECTED]> wrote:
  

it could be that 3.0 is using "banker's rounding" --- rounding to the
even digit.  the idea behind it behind it being to reduce error
accumulation when working with large sets of values.



Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo
CPU".  What system are you on?
  
It could be that 2.5 is really 2.4... which would round down to 2,

but on any modern CPU (using IEEE floating point), 2.5 should be
representable exactly.
  



That's exactly what's happening, pigmartian. Thank you for explaining
the reasoning behind this change.
So am I relegated to building my own round() function that behaves
like the original function? Or did they move the functionality to a
new method somewhere for backwards-compatibility?
  


This will work as you wish:
 math.floor(x+0.5)

Gary Herron



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


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


Re: I love "shelf" BUT

2008-07-27 Thread alex23
On Jul 28, 1:44 pm, Sera Jackson <[EMAIL PROTECTED]> wrote:
> Lot of thanks again, that's what I wanted to find, arguments against
> it, I was aware I wan not speaking of sth new.

Guido seems to keep hinting that someone should write a PEP, just so
it can be officially denied and then there'll be a place to point to
when the question arises again (as it inevitably will...)

So if you wanna take a shot... :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 6:21 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Russ P. wrote:
> > On Jul 27, 12:39 pm, Bruno Desthuilliers
> > All I am suggesting is that the programmer have the option of
> > replacing "self.member" with simply ".member", since the word "self"
> > is arbitrary and unnecessary.
>
> I presume you are proposing the opposite also, that ".member" would
> internally be expanded to "self.member".
>
> As I said before, that, or something near like it (it is hard to exactly
> compare underspecified proposals) has be suggested and rejected, even if
> someone gave you not the exact reference.  For one thing, as Guido
> noted, a single . can be hard to see and easy to miss, depending on
> one's eyesight, environmental lighting, and exact display medium,
> including font.
>
> I suspect Guido's other reasons have been covered, but I do not want
> misquote him.  I will leave you to search the pydev list archives.
>
>  > Otherwise, everything would work *EXACTLY* the same as it does now.
>
> If I understand you, that would mean that .attribute would raise
> NameError: name 'self' is not defined
> if used anywhere where 'self' was not defined.

After thinking about this a bit more, let me try to be more specific.

Forget about the empty first argument and the "." for the first
argument. Just let the first argument be "self" or anything the
programmer chooses. No change there.

If access is needed to "self.var", let it be accessable as either
"self.var" or simply ".var". Ditto for "self.method()", which would be
accessible as ".method()".

In other words, wherever ".var" appears, let it be interpreted as
".var". If the first argument is "self", then it should be
equivalent to "self.var". If the first argument is "snafu", then
".var" should be equivalent to "snafu.var".

I can't think of any technical problem with this proposal, but I may
be overlooking something. If so, please let me know.

This proposal should be relatively easy to implement, and it would
reduce code clutter significantly. (I could probably write a pre-
processor to implement myself it in less than a day.)
--
http://mail.python.org/mailman/listinfo/python-list


Command line arguements

2008-07-27 Thread aditya shukla
Hello folks ,I have a program in which a text file is generated as an output
eg

C:\prog\ prog -x test.txt
Right now whenever i have to read the test file i have to put its name
manually in my code.
eg
f=open("c:\\prog\\test.txt","r")

How ever i want to add the name of the test file dynamically to my program
ie , if every time i give

C:\prog\ prog -x test.txt
The filename (test.txt) automatically comes in
f=open("c:\\prog\\test.txt","r")

C:\prog\ prog -x file1.txt
f=open("c:\\prog\\file1","r")


in other words i do not want to do hard code the name of the file in my code
every time i need to read it.

I was reading about the sys module and i guess sys.argv would take the input
from the command line whenever i run the python script .

Please guide me in the right direction on how to tackle the problem.

Thanks in advance

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

Re: How to find processes from Python

2008-07-27 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, Johny
wrote:

> Is there a way how to find out  running processes?E.g. how many
> Appache's processes are running?

Under Linux, every process has a procfs directory /proc/, where 
is the process ID. In here you will find all kinds of interesting
information about the process command line, what files it has open, its
environment, its memory usage etc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python program as daemon?

2008-07-27 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>,
sturlamolden wrote:

> Basically it forks twice ...

What's the advantage of forking twice over forking once and calling setsid?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread castironpi
On Jul 27, 2:39 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Derek Martin a écrit :
> > It's bad programming, but the world is full of bad programmers, and we
> > don't always have the choice not to use their code.  Isn't one of
> > Python's goals to minimize opportunities for bad programming?
>
> Nope. That's Java's goal. Python's goals are to maximize opportunities
> for good programming, which is quite different.

+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> On Jul 26, 6:47 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
> central.gen.new_zealand> wrote:
>> In message
>> <[EMAIL PROTECTED]>,
>>
>> [EMAIL PROTECTED] wrote:
>> > On Jul 24, 5:01 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
>> > central.gen.new_zealand> wrote:
>>
>> >> In message
>> >> <[EMAIL PROTECTED]>,
>> >> Jordan wrote:
>>
>> >> > Except when it comes to Classes. I added some classes to code that
>> >> > had previously just been functions, and you know what I did - or
>> >> > rather, forgot to do? Put in the 'self'. In front of some of the
>> >> > variable accesses, but more noticably, at the start of *every single
>> >> > method argument list.*
>>
>> >> The reason is quite simple. Python is not truly an "object-oriented"
>> >> language. It's sufficiently close to fool those accustomed to OO ways
>> >> of doing things, but it doesn't force you to do things that way. You
>> >> still have the choice. An implicit "self" would take away that choice.
>>
>> > By that logic, C++ is not OO.
>>
>> Yes it is, because it has "this".
> 
> You mean the keyword "this"? It's just a feature. How does that make a
> difference on being or not being OO?

Because it was one of the things the OP was complaining about (see above).
--
http://mail.python.org/mailman/listinfo/python-list


Re: I love "shelf" BUT

2008-07-27 Thread Sera Jackson
On Jul 28, 6:25 am, alex23 <[EMAIL PROTECTED]> wrote:
> On Jul 28, 12:46 pm, Sera Jackson <[EMAIL PROTECTED]> wrote:
>
> > ok, I know its an over discussed topic. Althought I understand why it
> > is there I cant constantly see it in my argument list in parenthesis.
>
> > can someone give me an insight of the cons of a syntax like this:
> > class Class:
> >     def self.method(arguments):
> >         etc, etc
>
> > In other words def method(self, arg1, arg2 ,argN) becomes->  def
> > self.method(arg1, arg2 ,argN)
>
> Did you bother to check the group? You would've noticed it's being
> discussed -right 
> now-:http://groups.google.com/group/comp.lang.python/browse_frm/thread/a5f...
>
> And this -exact- suggestion has been turned down by 
> Guido:http://mail.python.org/pipermail/python-3000/2006-April/000793.html

alex thank you very much!

I searched excessively python mailing list but unforurtunately I was
using  as query and I missed
it, although I knew it should had been there. I mostly found threads
insisting on a complete removal...

And I sincerely apologise for missing the discussion here, I was tired
digging python old mailing list. :D.

Lot of thanks again, that's what I wanted to find, arguments against
it, I was aware I wan not speaking of sth new.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread alex23
On Jul 28, 4:59 am, "Russ P." <[EMAIL PROTECTED]> wrote:
> On Jul 27, 3:11 am, alex23 <[EMAIL PROTECTED]> wrote:
>
> > On Jul 27, 4:26 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
>
> > > On Jul 26, 11:18 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> > > > The use of '.' has been suggested before and rejected.
>
> > > Where and why?
>
> > Google is your 
> > friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html
>
> What Guido rejected there is most certainly *not*
> what I suggested. I agree with Guido on that one.

Orly?

Ian Bicking wrote: "I propose that the self argument be removed from
method definitions."

Philip Eby suggested:
>  def .aMethod(arg1, arg2):
>  return .otherMethod(arg1*2+arg2)

Guido shot them all down by stating:
> [Y]ou're proposing to hide a
> fundamental truth in Python, that methods are "just" functions whose
> first argument can be supplied using syntactic sugar

Any more reading comprehension we can do for you?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Derek Martin
On Sun, Jul 27, 2008 at 09:39:26PM +0200, Bruno Desthuilliers wrote:
> >As for the latter part of #3, self (or some other variable) is
> >required in the parameter list of object methods,
> 
> It's actually the parameter list of the *function* that is used as the 
> implementation of a method. Not quite the same thing. 

The idea that Python behaves this way is new to me.  For example, the
tutorials make no mention of it:

  http://docs.python.org/tut/node11.html#SECTION001130

The Python reference manual has very little to say about classes,
indeed.  If it's discussed there, it's buried somewhere I could not
easily find it.

> consistency mandates that the target object of the method is part of
> the parameter list of the *function*, since that's how you make
> objects availables to a function.

Fair enough, but I submit that this distinction is abstruse, and
poorly documented, and also generally not something the average
application developer should want to or have to care about... it's of
interest primarily to computer scientists and language enthusiasts.
The language should prefer to hide such details from the people using
it.

> >however when the method is *called*, it is omitted.
> 
> Certainly not. 

Seems not so certain to me...  We disagree, even after your careful
explanation.  See below.

> You need to lookup the corresponding attribute *on a given object*
> to get the method. Whether you write
> 
>   some_object.some_method()
> 
> or
> 
>   some_function(some_object)
> 
> you still need to explicitely mention some_object.

But these two constructs are conceptually DIFFERENT, whether or not
their implementation is the same or similar.  The first says that
some_method is defined within the name space of some_object.  The
second says that some_object is a parameter of some_function...

Namespace != parameter!

To many people previously familiar with OO programming in other
languages (not just Java or C++), but not intimately familiar with
Python's implementation details, the first also implies that
some_method is inherently part of some_object, in which case
explicitly providing a parameter to pass in the object naturally seems
kind of crazy.  The method can and should have implicit knowledge of
what object it has been made a part.  Part of the point of using
objects is that they do have special knowledge of themselves... they
(generally) manipulate data that's part of the object.  Conceptually,
the idea that an object's methods can be defined outside of the scope
of the object, and need to be told what object they are part
of/operating on is somewhat nonsensical...

> >Thus when an object method is called, it must be called with one fewer
> >arguments than those which are defined.   This can be confusing,
> >especially to new programmers.
> 
> This is confusing as long as you insist on saying that what you 
> "def"ined is a method - which is not the case.

I can see now the distinction, but please pardon my prior ignorance,
since the documentation says it IS the case, as I pointed out earlier.
Furthermore, as you described, defining the function within the scope
of a class binds a name to the function and then makes it a method of
the class.  Once that happens, *the function has become a method*.

To be perfectly honest, the idea that an object method can be defined
outside the scope of an object (i.e. where the code has no reason to
have any knowledge of the object) seems kind of gross to me... another
Python wart.  One which could occasionally be useful I suppose, but a
wart nonetheless.  This seems inherently not object-oriented at all,
for reasons I've already stated.  It also strikes me as a feature
designed to encourage bad programming practices.

Even discounting that, if Python had a keyword which referenced the
object of which a given peice of code was a part, e.g. self, then a
function written to be an object method could use this keyword *even
if it is defined outside of the scope of a class*.  The self keyword,
once the function was bound to an object, would automatically refer to
the correct object.  If the function were called outside of the
context of an object, then referencing self would result in an
exception.

You'll probably argue that this takes away your ability to define a
function and subsequently use it both as a stand-alone function and
also as a method.  I'm OK with that -- while it might occasionally
be useful, I think if you feel the need to do this, it probably means
your program design is wrong/bad.  More than likely what you really
needed was to define a class that had the function as a method, and
another class (or several) that inherits from the first.


> The point is that you don't get access to the object "within itself". 
> You get access to an object *within a function*.

Thus methods are not really methods at all, which would seem to
suggest that Python's OO model is inherently broken (albeit by design,
and perhaps occasionally t

Re: I love "shelf" BUT

2008-07-27 Thread alex23
On Jul 28, 12:46 pm, Sera Jackson <[EMAIL PROTECTED]> wrote:
> ok, I know its an over discussed topic. Althought I understand why it
> is there I cant constantly see it in my argument list in parenthesis.
>
> can someone give me an insight of the cons of a syntax like this:
> class Class:
>     def self.method(arguments):
>         etc, etc
>
> In other words def method(self, arg1, arg2 ,argN) becomes->  def
> self.method(arg1, arg2 ,argN)

Did you bother to check the group? You would've noticed it's being
discussed -right now-:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/a5fa8ff0ffadd6ee/60e9dd04719e439a

And this -exact- suggestion has been turned down by Guido:
http://mail.python.org/pipermail/python-3000/2006-April/000793.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 3:54 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 27 Jul 2008 12:33:16 -0700, Russ P. wrote:
> > On Jul 27, 1:19 am, Steven D'Aprano <[EMAIL PROTECTED]
> > cybersource.com.au> wrote:
> >> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote:
>
> >> > You take the name down to a single letter. As I suggested in an
> >> > earlier post on this thread, why not take it down to zero letters?
>
> >> The question isn't "why not", but "why". The status quo works well as
> >> it is, even if it isn't perfect. Prove that implicit self is a good
> >> idea -- or at least prove that it is an idea worth considering.
>
> >> "I don't like typing self" doesn't convince me. The same argument could
> >> be made typing parentheses, colons, commas, etc. We could end up with
> >> something like this:
>
> >> class Foo base
> >> def method x y z
> >> .args = list x y z
>
> >> That's not necessarily wrong, but it's not Python.
>
> > And what does that have to do with my suggestion? Absolutely nothing.
>
> Not at all. You're suggesting a change to Python's syntax. I've suggested
> a couple more changes to Python syntax. I don't intend them to be taken
> seriously, but only to illustrate a point that syntax defines how a
> language is written. You want to change that.

But the syntax change I am suggesting is trivial compared to the
draconian examples you gave.

> > It's a red herring that you seem to be using to obscure the fact that
> > you have no rational argument to make.
>
> I don't have to make a rational argument for keeping the status quo. That
> status quo just *is*. You want people to change, you need to convince
> them that such a change is not just "not bad" but a serious advantage,
> enough to make up for all the work required to implement it.

> I'm listening. Tell me why removing self if not merely harmless, but
> actively better.
>
> [...]

I thought I did just that. I am very meticulous about the appearance
of my code, and the less cluttered the better. That's one of the main
reasons that I use Python. My suggestion would be relatively trivial
to implement, yet it would dramatically reduce clutter. You may not
agree, but I think the case is strong.

> >> By "better" do you mean "uglier"? If so, I agree with you. If not, then
> >> I disagree that it is better.
>
> > You seem to be freaked out by an empty argument. Actually, it bothers me
> > a bit too, which is why I suggested that a period could be used as the
> > first argument to indicate that, like Clint Eastwood in The Good, the
> > Bad, and the Ugly, "self" had no name here.
>
> Well there you go now. How should we *talk* about this piece of code? Try
> writing a comment or docstring, or even sitting down with a fellow
> programmer and discussing it. What do you call this implicit Object With
> No Name?

How do Java and C++ programmers talk about the instance for which the
method was called? I wasn't aware that that was a problem for them.

> def fun( , cat):
> .cat = cat  # assumes that the Object With No Name has foo
>
> versus
>
> def fun(self, cat):
> self.cat = cat  # assumes that self has foo
>
> Before you suggest that people will continue to call the first argument
> "self" but just not write it down anywhere, I suggest that's a terrible
> idea and one which will confuse a lot of people. "Where's this 'self'
> defined? I can't find it anywhere!"

Any programmer who can't get past that point needs to find a new line
of work -- such as moving furniture.

> A slightly better suggestion is "the instance", but that fails here:
>
> class C(object):
> def method(, other):
> assert isinstance(other, C)
> .cat = other  # assumes that the instance has foo
> # er, that is to say, the implicit instance,
> # not the other instance
>
> The ability to talk easily about the code is invaluable. Implicit self
> makes it harder to talk about the code.

I can only imagine what you must think about lambda functions and list
comprehensions.

> [...]
>
> >> Even uglier than the first. Convince me there's a benefit.
>
> > Actually, I think it's elegant. And I'll bet that if Guido had suggested
> > it, you would think it was beautiful.
>
> Oh please. I think the syntax for ternary if is ugly, and Guido came up
> with that, and it doesn't even use punctuation.

Off topic, but I happen to like Guido's ternary "if." I use it
wherever I can, within reason.

> > Why force a name to be used when none is needed?
>
> But a name is needed.
>
> class Foo(base1, base2, base3):
> def meth(self, arg):
> super(Foo, self).meth(arg)
> print self
> try:
> value = _cache[self]
> except KeyError:
> value = some_long_calculation(self)
>
> How do you pass self to arbitrary functions without a name?

I didn't say you *never* need the name. If you need it, then use it.
But if you don't need it, you shouldn't be forced to use a name just
for the sake

Re: Where is the correct round() method?

2008-07-27 Thread Paul McGuire
On Jul 27, 8:55 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> josh logan wrote:
> > Hello,
>
> > I need a round function that _always_ rounds to the higher integer if
> > the argument is equidistant between two integers. In Python 3.0, this
> > is not the advertised behavior of the built-in function round() as
> > seen below:
>
>  round(0.5)
> > 0
>  round(1.5)
> > 2
>  round(2.5)
> > 2
>
> > I would think this is a common need, but I cannot find a function in
> > the Python library to do it. I wrote my own, but did I miss such a
> > method in my search of the Python library?
>
> > Thanks
>
> I think what you want is something like:
>
> math.ceil(x-0.4)
>
> -Larry- Hide quoted text -
>
> - Show quoted text -

The version I learned back in my FORTRAN days was:

int(x + 0.5)

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


I love "shelf" BUT

2008-07-27 Thread Sera Jackson
ok, I know its an over discussed topic. Althought I understand why it
is there I cant constantly see it in my argument list in parenthesis.

can someone give me an insight of the cons of a syntax like this:
class Class:
def self.method(arguments):
etc, etc


In other words def method(self, arg1, arg2 ,argN) becomes->  def
self.method(arg1, arg2 ,argN)

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


Re: write unsigned integer 32 bits to socket

2008-07-27 Thread [EMAIL PROTECTED]
On Sun, Jul 27, 2008 at 7:17 PM, Larry Bates <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates <[EMAIL PROTECTED]>
>> wrote:
>>> [EMAIL PROTECTED] wrote:
 i want to send unsigned 32 bit integer to socket, and looking for
 something equivalent to this method...

 http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt()

 is there such method / library available in python?!
>>>
>>> You will need to use struct module to build the 4 byte value and then
>>> send
>>> it.
>>>
>>> Something like (not tested):
>>>
>>> import struct
>>> us32bit = struct.pack("I", value)
>>> s.send(us32bit)
>>
>> thanks a lot!!!
>>
>> just to make sure if I want 32 bit or 4 bytes then should I use the
>> short or integer or long?
>>
>> this is short
>
> struct.pack('!h',3)
>>
>> '\x00\x03'
>>
>> this is integer
>
> struct.pack('!i',3)
>>
>> '\x00\x00\x00\x03'
>>
>> this is long
>
> struct.pack('!l',3)
>>
>> '\x00\x00\x00\x03'
>
> Short is 16 bits, Integer is 32 bits, long is 64 bits (as I read and have
> found).
thanks a lot!!! re-read it again!!!

from the struct doc!
Standard size and alignment are as follows: no alignment is required
for any type (so you have to use pad bytes); short is 2 bytes; int and
long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and
double are 32-bit and 64-bit IEEE floating point numbers,
respectively.
--
http://mail.python.org/mailman/listinfo/python-list


Re: write unsigned integer 32 bits to socket

2008-07-27 Thread Larry Bates

[EMAIL PROTECTED] wrote:

On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates <[EMAIL PROTECTED]> wrote:

[EMAIL PROTECTED] wrote:

i want to send unsigned 32 bit integer to socket, and looking for
something equivalent to this method...
http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt()

is there such method / library available in python?!

You will need to use struct module to build the 4 byte value and then send
it.

Something like (not tested):

import struct
us32bit = struct.pack("I", value)
s.send(us32bit)


thanks a lot!!!

just to make sure if I want 32 bit or 4 bytes then should I use the
short or integer or long?

this is short

struct.pack('!h',3)

'\x00\x03'

this is integer

struct.pack('!i',3)

'\x00\x00\x00\x03'

this is long

struct.pack('!l',3)

'\x00\x00\x00\x03'


Short is 16 bits, Integer is 32 bits, long is 64 bits (as I read and have 
found).

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


Re: write unsigned integer 32 bits to socket

2008-07-27 Thread [EMAIL PROTECTED]
On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> i want to send unsigned 32 bit integer to socket, and looking for
>> something equivalent to this method...
>> http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt()
>>
>> is there such method / library available in python?!
> You will need to use struct module to build the 4 byte value and then send
> it.
>
> Something like (not tested):
>
> import struct
> us32bit = struct.pack("I", value)
> s.send(us32bit)

thanks a lot!!!

just to make sure if I want 32 bit or 4 bytes then should I use the
short or integer or long?

this is short
>>> struct.pack('!h',3)
'\x00\x03'

this is integer
>>> struct.pack('!i',3)
'\x00\x00\x00\x03'

this is long
>>> struct.pack('!l',3)
'\x00\x00\x00\x03'
--
http://mail.python.org/mailman/listinfo/python-list


Re: write unsigned integer 32 bits to socket

2008-07-27 Thread Larry Bates

[EMAIL PROTECTED] wrote:

hi
i want to send unsigned 32 bit integer to socket, and looking for
something equivalent to this method...

http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt()

is there such method / library available in python?!


this is as far as i have gotten along

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',3000))


You will need to use struct module to build the 4 byte value and then send it.

Something like (not tested):

import struct
us32bit = struct.pack("I", value)
s.send(us32bit)

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


Re: like py2exe, but on a mac

2008-07-27 Thread William McBrine
On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote:

> http://undefined.org/python/py2app.html

py2app bundles Python itself into the app, right? I wonder, is there no 
way to create an app bundle that relies on the existing installation of 
Python, since OS X already comes with Python? I have a tiny little 
program (~20k) that I'd like to make into an app bundle, if only to 
suppress the console window, and I'd rather not lump in the whole Python 
interpreter if I can avoid it.

-- 
09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the correct round() method?

2008-07-27 Thread Larry Bates

josh logan wrote:

Hello,

I need a round function that _always_ rounds to the higher integer if
the argument is equidistant between two integers. In Python 3.0, this
is not the advertised behavior of the built-in function round() as
seen below:


round(0.5)

0

round(1.5)

2

round(2.5)

2


I would think this is a common need, but I cannot find a function in
the Python library to do it. I wrote my own, but did I miss such a
method in my search of the Python library?

Thanks


I think what you want is something like:

math.ceil(x-0.4)

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


Re: Where is the correct round() method?

2008-07-27 Thread Terry Reedy



Gary Herron wrote:

josh logan wrote:



I need a round function that _always_ rounds to the higher integer if
the argument is equidistant between two integers. In Python 3.0, this
is not the advertised behavior of the built-in function round() as
seen below:



round(2.5)


2



Huh?
 >>> round(2.5)
3.0


As the OP said, PY 3.0, where statisticians' unbiased round to even was 
explicitly adopted.  (I think before it was maybe left to the C library?)



I would think this is a common need,


If you need any particular rounding for legal/finance-rule reasons, you 
probably need the decimal module, which has several rounding modes and 
other features catering to money calculation rules.


For general data analysis with floats, round to even is better.

tjr

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


write unsigned integer 32 bits to socket

2008-07-27 Thread [EMAIL PROTECTED]
hi
i want to send unsigned 32 bit integer to socket, and looking for
something equivalent to this method...

http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt()

is there such method / library available in python?!


this is as far as i have gotten along
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('127.0.0.1',3000))
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Terry Reedy



Russ P. wrote:


When I write a function in which a data member will be used several
times, I usually do something like this:

data = self.data

so I can avoid the clutter of repeated use of "self.data".


Another reason people do this is for speed, even if self.data is used 
just once but in a loop.


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


Re: Attack a sacred Python Cow

2008-07-27 Thread Terry Reedy

Russ P. wrote:

On Jul 27, 12:39 pm, Bruno Desthuilliers



All I am suggesting is that the programmer have the option of
replacing "self.member" with simply ".member", since the word "self"
is arbitrary and unnecessary.


I presume you are proposing the opposite also, that ".member" would 
internally be expanded to "self.member".


As I said before, that, or something near like it (it is hard to exactly 
compare underspecified proposals) has be suggested and rejected, even if 
someone gave you not the exact reference.  For one thing, as Guido 
noted, a single . can be hard to see and easy to miss, depending on 
one's eyesight, environmental lighting, and exact display medium, 
including font.


I suspect Guido's other reasons have been covered, but I do not want 
misquote him.  I will leave you to search the pydev list archives.


> Otherwise, everything would work *EXACTLY* the same as it does now.

If I understand you, that would mean that .attribute would raise
NameError: name 'self' is not defined
if used anywhere where 'self' was not defined.

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


ctypes - unloading implicitly loaded dlls

2008-07-27 Thread pigmartian
(my apologies if this is a repost, but it sure seems like the first 
attempt disappeared into the ether...)


I'm writing a program that uses functionality from two different sets of 
cdlls which reside in two different directories, call them 'libA.dll' 
and 'libB.dll'.  Although I don't directly use it, both directories 
contain a dll with the same name, although they aren't in fact 
identical.  Call them, "libC.dll".  However, the c-functions I call from 
the clls I do use seem to implicitly use "libC.dll".  The problem that 
occurs after I load one dll and call functions in it, when I try to load 
the second dll I get windows errors because the second dll tries to call 
a function in its version of libC.dll, but it finds the version meant 
for libB.dll, which doesn't contain that function.


Oy, I hope some sample code makes it clearer:

def demo():

 A = ctypes.cdll.LoadLibrary('/path1/libA.dll')
 A.foo() # implicitly uses '/path1/libC.dll'

 _ctypes.FreeLibrary(A._handle)

 # CRASH!
 B = ctypes.cdll.LoadLibrary('/path2/libB.dll')
 # "The procedure entry point some_func could not be located
 # in the dynamic link library libC.dll.":

 # libB.dll wants to use code from '/path2/libC.dll', but
 # instead it finds '/path1/libC.dll' already loaded
 # in memory, which doesn't
 # contain the function call it wants.


Assuming my understanding of things is correct, then I believe what I 
need to do is to remove /path1/libC.dll from memory before I try loading 
libB.dll, but I haven't found any way of doing that.  Can anyone offer 
my some suggestions?  Or, am I S.O.L.?



Notes:
* the two sets of dlls are supplied by a vendor for working with its 
COTS packages; I don't have any control over the dll names used or the 
code therein.
* If I leave out the call to A.foo(), then I don't crash, but if I leave 
out the FreeLibrary call as well then I do crash.

* I've tried manipulating the PATH before loading the dlls, to no effect.
* I've tried del'ing A and running gc.collect() before loading B.

Thanks,

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


Re: Where is the correct round() method?

2008-07-27 Thread josh logan
On Jul 27, 8:45 pm, pigmartian <[EMAIL PROTECTED]> wrote:
> it could be that 3.0 is using "banker's rounding" --- rounding to the
> even digit.  the idea behind it behind it being to reduce error
> accumulation when working with large sets of values.
>
> > Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo
> > CPU".  What system are you on?
>
> > It could be that 2.5 is really 2.4... which would round down to 2,
> > but on any modern CPU (using IEEE floating point), 2.5 should be
> > representable exactly.
>
>

That's exactly what's happening, pigmartian. Thank you for explaining
the reasoning behind this change.
So am I relegated to building my own round() function that behaves
like the original function? Or did they move the functionality to a
new method somewhere for backwards-compatibility?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the correct round() method?

2008-07-27 Thread josh logan
On Jul 27, 7:58 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> josh logan wrote:
> > Hello,
>
> > I need a round function that _always_ rounds to the higher integer if
> > the argument is equidistant between two integers. In Python 3.0, this
> > is not the advertised behavior of the built-in function round() as
> > seen below:
>
>  round(0.5)
>
> > 0
>
>  round(1.5)
>
> > 2
>
>  round(2.5)
>
> > 2
>
> Huh?
>
>  >>> round(2.5)
> 3.0
>
> Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo
> CPU".  What system are you on?
>
> It could be that 2.5 is really 2.4... which would round down to 2,
> but on any modern CPU (using IEEE floating point), 2.5 should be
> representable exactly.
>
> However, as with any floating point calculations, if you expect exact
> representation or calculations with any numbers, then you are misusing
> floating points.
>
> Gary Herron
>
> > I would think this is a common need, but I cannot find a function in
> > the Python library to do it. I wrote my own, but did I miss such a
> > method in my search of the Python library?
>
> > Thanks
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

I should reiterate that I am using Python 3.0 and not Python 2.x.
It looks like the behavior round() has changed between these two
versions.
Here is the documentation for round() in Python 3.0:
http://docs.python.org/dev/3.0/library/functions.html#round

Of interest in this discussion is the second paragraph, which explains
the change:

Does anyone know the reason behind this change, and what replacement
method I can use to get the original behavior?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the correct round() method?

2008-07-27 Thread pigmartian
it could be that 3.0 is using "banker's rounding" --- rounding to the 
even digit.  the idea behind it behind it being to reduce error 
accumulation when working with large sets of values.



Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo 
CPU".  What system are you on?



It could be that 2.5 is really 2.4... which would round down to 2, 
but on any modern CPU (using IEEE floating point), 2.5 should be 
representable exactly.




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


Re: Where is the correct round() method? Use math.ceil

2008-07-27 Thread Herman
>
> Where is the correct round() method?
> Hello,
>
> I need a round function that _always_ rounds to the higher integer if
> the argument is equidistant between two integers. In Python 3.0, this
> is not the advertised behavior of the built-in function round() as
> seen below:
>
> >>> round(0.5)
> 0
> >>> round(1.5)
> 2
> >>> round(2.5)
> 2
>
>
> I would think this is a common need, but I cannot find a function in
> the Python library to do it. I wrote my own, but did I miss such a
> method in my search of the Python library?
>
> Thanks


Use ceil in the math module:
import math
math.ceil(number)
--
http://mail.python.org/mailman/listinfo/python-list

Re: Where is the correct round() method?

2008-07-27 Thread Gary Herron

josh logan wrote:

Hello,

I need a round function that _always_ rounds to the higher integer if
the argument is equidistant between two integers. In Python 3.0, this
is not the advertised behavior of the built-in function round() as
seen below:

  

round(0.5)


0
  

round(1.5)


2
  

round(2.5)


2

  


Huh?

>>> round(2.5)
3.0


Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo 
CPU".  What system are you on?



It could be that 2.5 is really 2.4... which would round down to 2, 
but on any modern CPU (using IEEE floating point), 2.5 should be 
representable exactly.


However, as with any floating point calculations, if you expect exact 
representation or calculations with any numbers, then you are misusing 
floating points. 


Gary Herron


I would think this is a common need, but I cannot find a function in
the Python library to do it. I wrote my own, but did I miss such a
method in my search of the Python library?

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


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


Re: Not entirely serious: recursive lambda?

2008-07-27 Thread Cameron Simpson
On 20Jul2008 00:08, Kay Schluehr <[EMAIL PROTECTED]> wrote:
| > Google was not my friend on this one, and I suspect there is no
| > answer.
| 
| Even the Great Google can't help if you don't use the right
| keywords ;)

Actually, I was shown an useful Google search syntax the other day:

Searching for:

  foo

looks just for "foo", but searching for:

  ~foo

matches similar words.

This came up in a discussion of web sites that use badly chosen keywords (the
NSW Police gun licensing information talks only about "firearms", making it
surprisingly hard to find; not that I have or want a gun license, but it was
the example discussed).

Cheers,
-- 
Cameron Simpson <[EMAIL PROTECTED]> DoD#743
http://www.cskk.ezoshosting.com/cs/

Humans are incapable of securely storing high quality cryptographic
keys and they have unacceptable speed and accuracy when performing
cryptographic operations.  (They are also large, expensive to maintain
diffcult to manage and they pollute the environment.) It is astonishing
that these devices continue to be manufactured and deployed. But they
are suffciently pervasive that we must design our protocols around
their limitations.  - C Kaufman, R Perlman, M Speciner
  _Network Security: PRIVATE Communication in a
   PUBLIC World_, Prentice Hall, 1995, pp. 205.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Steven D'Aprano
On Sun, 27 Jul 2008 16:04:43 -0400, Colin J. Williams wrote:

>> For those who don't like the way the empty first argument looks, maybe
>> something like this could be allowed:
>> 
>> def fun( ., cat):
>> 
> I don't see the need for the comma in fun.


Or the parentheses and colon. Can we remove them too?


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


Re: Attack a sacred Python Cow

2008-07-27 Thread Steven D'Aprano
On Sun, 27 Jul 2008 12:33:16 -0700, Russ P. wrote:

> On Jul 27, 1:19 am, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote:
> 
>> > You take the name down to a single letter. As I suggested in an
>> > earlier post on this thread, why not take it down to zero letters?
>>
>> The question isn't "why not", but "why". The status quo works well as
>> it is, even if it isn't perfect. Prove that implicit self is a good
>> idea -- or at least prove that it is an idea worth considering.
>>
>> "I don't like typing self" doesn't convince me. The same argument could
>> be made typing parentheses, colons, commas, etc. We could end up with
>> something like this:
>>
>> class Foo base
>> def method x y z
>> .args = list x y z
>>
>> That's not necessarily wrong, but it's not Python.
> 
> And what does that have to do with my suggestion? Absolutely nothing.

Not at all. You're suggesting a change to Python's syntax. I've suggested 
a couple more changes to Python syntax. I don't intend them to be taken 
seriously, but only to illustrate a point that syntax defines how a 
language is written. You want to change that.


> It's a red herring that you seem to be using to obscure the fact that
> you have no rational argument to make.

I don't have to make a rational argument for keeping the status quo. That 
status quo just *is*. You want people to change, you need to convince 
them that such a change is not just "not bad" but a serious advantage, 
enough to make up for all the work required to implement it.

I'm listening. Tell me why removing self if not merely harmless, but 
actively better.

[...]


>> By "better" do you mean "uglier"? If so, I agree with you. If not, then
>> I disagree that it is better.
> 
> You seem to be freaked out by an empty argument. Actually, it bothers me
> a bit too, which is why I suggested that a period could be used as the
> first argument to indicate that, like Clint Eastwood in The Good, the
> Bad, and the Ugly, "self" had no name here.

Well there you go now. How should we *talk* about this piece of code? Try 
writing a comment or docstring, or even sitting down with a fellow 
programmer and discussing it. What do you call this implicit Object With 
No Name?

def fun( , cat):
.cat = cat  # assumes that the Object With No Name has foo

versus

def fun(self, cat):
self.cat = cat  # assumes that self has foo

Before you suggest that people will continue to call the first argument 
"self" but just not write it down anywhere, I suggest that's a terrible 
idea and one which will confuse a lot of people. "Where's this 'self' 
defined? I can't find it anywhere!"

A slightly better suggestion is "the instance", but that fails here:

class C(object):
def method(, other):
assert isinstance(other, C)
.cat = other  # assumes that the instance has foo
# er, that is to say, the implicit instance, 
# not the other instance


The ability to talk easily about the code is invaluable. Implicit self 
makes it harder to talk about the code.


[...]

>> Even uglier than the first. Convince me there's a benefit.
> 
> Actually, I think it's elegant. And I'll bet that if Guido had suggested
> it, you would think it was beautiful.

Oh please. I think the syntax for ternary if is ugly, and Guido came up 
with that, and it doesn't even use punctuation.

> Why force a name to be used when none is needed?

But a name is needed. 

class Foo(base1, base2, base3):
def meth(self, arg):
super(Foo, self).meth(arg)
print self
try:
value = _cache[self]
except KeyError:
value = some_long_calculation(self)


How do you pass self to arbitrary functions without a name?



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


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 3:11 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
> On Jul 27, 12:39 pm, Bruno Desthuilliers
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > Derek Martin a écrit :
>
> > > On Sun, Jul 27, 2008 at 08:19:17AM +, Steven D'Aprano wrote:
> > >>> You take the name down to a single letter. As I suggested in an earlier
> > >>> post on this thread, why not take it down to zero letters?
> > >> The question isn't "why not", but "why". The status quo works well as it
> > >> is, even if it isn't perfect. Prove that implicit self is a good idea --
> > >> or at least prove that it is an idea worth considering.
>
> > > Come on, this sounds like a schoolyard argument.  This comes down to a
> > > matter of style, and as such, is impossible to prove.  It's largely a
> > > question of individual preference.
>
> > > That said, the argument in favor is rather simple:
>
> > > 1. This is an extremely common idiom in Python
> > > 2. It is completely unnecessary, and the language does not suffer for
> > >making it implicit
> > > 3. Making it implicit reduces typing, reduces opportunities for
> > >mistakes, and arguably increases consistency.
>
> > "arguably", indeed, cf below.
>
> > > As for the latter part of #3, self (or some other variable) is
> > > required in the parameter list of object methods,
>
> > It's actually the parameter list of the *function* that is used as the
> > implementation of a method. Not quite the same thing. And then,
> > consistency mandates that the target object of the method is part of the
> > parameter list of the *function*, since that's how you make objects
> > availables to a function.
>
> > > however when the
> > > method is *called*, it is omitted.
>
> > Certainly not. You need to lookup the corresponding attribute *on a
> > given object* to get the method. Whether you write
>
> >some_object.some_method()
>
> > or
>
> >some_function(some_object)
>
> > you still need to explicitely mention some_object.
>
> > > It is implied, supplied by Python.
>
> > Neither. The target object is passed to the function by the method
> > object, which is itself returned by the __get__ method of function
> > objects, which is one possible application of the more general
> > descriptor protocol (the same protocol that is used for computed
> > attributes). IOW, there's nothing specific to 'methods' here, just the
> > use of two general features (functions and the descriptor protocol).
> > FWIW, you can write your own callable, and write it so it behave just
> > like a function here:
>
> > import types
>
> > class MyCallable(object):
> > def __call__(self, obj):
> > print "calling %s with %s" % (self, obj)
> > def __get__(self, instance, cls):
> > return types.MethodType(self.__call__, instance, cls)
>
> > class Foo(object):
> >  bar = MyCallable()
>
> > print Foo.bar
> > f = Foo()
> > f.bar()
>
> > > Thus when an object method is called, it must be called with one fewer
> > > arguments than those which are defined.   This can be confusing,
> > > especially to new programmers.
>
> > This is confusing as long as you insist on saying that what you
> > "def"ined is a method - which is not the case.
>
> > > It can also be argued that it makes the code less ugly, though again,
> > > that's a matter of preference.
>
> > >> It's not enough to show that a change "isn't bad" -- you have to show
> > >> that it is actively good.
>
> > > But he did... he pointed out that *it saves work*, without actually
> > > being bad.  Benefit, without drawback.  Sounds good to me!
>
> > >> "Don't need to look at the method signature" is not an argument in favour
> > >> of implicit self.
>
> > > Yes, actually, it is.
>
> > It isn't, since there's no "method signature" to look at !-)
>
> > >  If there is a well-defined feature of Python
> > > which provides access to the object within itself,
>
> > The point is that you don't get access to the object "within itself".
> > You get access to an object *within a function*.
>
> > The fact that a function is defined within a class statement doesn't
> > imply any "magic", it just creates a function object, bind it to a name,
> > and make that object an attribute of the class. You have the very same
> > result by defining the function outside the class statement and binding
> > it within the class statement, by defining the function outside the
> > class and binding it to the class outside the class statement, by
> > binding the name to a lambda within the class statement etc...
>
> > > then the
> > > opportunities for mistakes when someone decides to use something else
> > > are lessened.
>
> > >> You don't need to look at the method signature when you're using an
> > >> explicit self either.
>
> > > That isn't necessarily true.  If you're using someone else's code, and
> > > they didn't use "self" -- or worse yet, if they chose this variable's
> > > name randomly throughout their classes -- then you may well need to
> > > look back to see what was used.
>

Re: Confounded by Python objects

2008-07-27 Thread Steven D'Aprano
On Sun, 27 Jul 2008 20:04:27 +0200, Bruno Desthuilliers wrote:

>> In general, anything that looks like this:
>> 
>> s = ''
>> for i in range(1):  # or any big number
>> s = s + 'another string'
>> 
>> can be slow. Very slow.
> 
> But this is way faster:
> 
> s = ''
> for i in range(1):  # or any big number
>  s += 'another string'

Actually, no, for two reasons:

(1) The optimizer works with both s = s+t and s += t, so your version is 
no faster than mine.

(2) The optimization isn't part of the language. It only happens if you 
are using CPython versions better than 2.4, and even then not guaranteed.

People forget that CPython isn't the language, it's just one 
implementation of the language, like Jython and IronPython. Relying on 
the optimization is relying on an implementation-specific trick.

> yeps : using augmented assignment (s =+ some_string) instead of
> concatenation and rebinding (s = s + some_string).

Both are equally optimized.

>>> timeit.Timer('s+=t', 's,t="xy"').repeat(number=10)
[0.027187108993530273, 0.026471138000488281, 0.027689933776855469]
>>> timeit.Timer('s=s+t', 's,t="xy"').repeat(number=10)
[0.026300907135009766, 0.02638697624206543, 0.02637791633605957]

But here's a version without it:

>>> timeit.Timer('s=t+s', 's,t="xy"').repeat(number=10)
[2.1038830280303955, 2.1027638912200928, 2.1031770706176758]



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


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 12:39 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Derek Martin a écrit :
>
>
>
> > On Sun, Jul 27, 2008 at 08:19:17AM +, Steven D'Aprano wrote:
> >>> You take the name down to a single letter. As I suggested in an earlier
> >>> post on this thread, why not take it down to zero letters?
> >> The question isn't "why not", but "why". The status quo works well as it
> >> is, even if it isn't perfect. Prove that implicit self is a good idea --
> >> or at least prove that it is an idea worth considering.
>
> > Come on, this sounds like a schoolyard argument.  This comes down to a
> > matter of style, and as such, is impossible to prove.  It's largely a
> > question of individual preference.
>
> > That said, the argument in favor is rather simple:
>
> > 1. This is an extremely common idiom in Python
> > 2. It is completely unnecessary, and the language does not suffer for
> >making it implicit
> > 3. Making it implicit reduces typing, reduces opportunities for
> >mistakes, and arguably increases consistency.
>
> "arguably", indeed, cf below.
>
> > As for the latter part of #3, self (or some other variable) is
> > required in the parameter list of object methods,
>
> It's actually the parameter list of the *function* that is used as the
> implementation of a method. Not quite the same thing. And then,
> consistency mandates that the target object of the method is part of the
> parameter list of the *function*, since that's how you make objects
> availables to a function.
>
> > however when the
> > method is *called*, it is omitted.
>
> Certainly not. You need to lookup the corresponding attribute *on a
> given object* to get the method. Whether you write
>
>some_object.some_method()
>
> or
>
>some_function(some_object)
>
> you still need to explicitely mention some_object.
>
> > It is implied, supplied by Python.
>
> Neither. The target object is passed to the function by the method
> object, which is itself returned by the __get__ method of function
> objects, which is one possible application of the more general
> descriptor protocol (the same protocol that is used for computed
> attributes). IOW, there's nothing specific to 'methods' here, just the
> use of two general features (functions and the descriptor protocol).
> FWIW, you can write your own callable, and write it so it behave just
> like a function here:
>
> import types
>
> class MyCallable(object):
> def __call__(self, obj):
> print "calling %s with %s" % (self, obj)
> def __get__(self, instance, cls):
> return types.MethodType(self.__call__, instance, cls)
>
> class Foo(object):
>  bar = MyCallable()
>
> print Foo.bar
> f = Foo()
> f.bar()
>
> > Thus when an object method is called, it must be called with one fewer
> > arguments than those which are defined.   This can be confusing,
> > especially to new programmers.
>
> This is confusing as long as you insist on saying that what you
> "def"ined is a method - which is not the case.
>
> > It can also be argued that it makes the code less ugly, though again,
> > that's a matter of preference.
>
> >> It's not enough to show that a change "isn't bad" -- you have to show
> >> that it is actively good.
>
> > But he did... he pointed out that *it saves work*, without actually
> > being bad.  Benefit, without drawback.  Sounds good to me!
>
> >> "Don't need to look at the method signature" is not an argument in favour
> >> of implicit self.
>
> > Yes, actually, it is.
>
> It isn't, since there's no "method signature" to look at !-)
>
> >  If there is a well-defined feature of Python
> > which provides access to the object within itself,
>
> The point is that you don't get access to the object "within itself".
> You get access to an object *within a function*.
>
> The fact that a function is defined within a class statement doesn't
> imply any "magic", it just creates a function object, bind it to a name,
> and make that object an attribute of the class. You have the very same
> result by defining the function outside the class statement and binding
> it within the class statement, by defining the function outside the
> class and binding it to the class outside the class statement, by
> binding the name to a lambda within the class statement etc...
>
> > then the
> > opportunities for mistakes when someone decides to use something else
> > are lessened.
>
> >> You don't need to look at the method signature when you're using an
> >> explicit self either.
>
> > That isn't necessarily true.  If you're using someone else's code, and
> > they didn't use "self" -- or worse yet, if they chose this variable's
> > name randomly throughout their classes -- then you may well need to
> > look back to see what was used.
>
> > It's bad programming, but the world is full of bad programmers, and we
> > don't always have the choice not to use their code.  Isn't one of
> > Python's goals to minimize opportunities for bad programming?
>
> Nope. That's Java's go

Taking command line arguments from another program

2008-07-27 Thread aditya shukla
Hello folks ,I have a program in which a text file is generated as an output
eg

C:\prog\ prog -x test.txt
Right now whenever i have to read the test file i have to put its name
manually in my code.
eg
f=open("c:\\prog\\test.txt","r")

How ever i want to add the name of the test file dynamically to my program
ie , if every time i give

C:\prog\ prog -x test.txt
The filename (test.txt) automatically comes in
f=open("c:\\prog\\test.txt","r")

C:\prog\ prog -x file1.txt
f=open("c:\\prog\\file1","r")


in other words i do not want to do hard code the name of the file in my code
every time i need to read it.

I was reading about the sys module and i guess sys.argv would take the input
from the command line whenever i run the python script .

Please guide me in the right direction on how to tackle the problem.

Thanks in advance

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

Where is the correct round() method?

2008-07-27 Thread josh logan
Hello,

I need a round function that _always_ rounds to the higher integer if
the argument is equidistant between two integers. In Python 3.0, this
is not the advertised behavior of the built-in function round() as
seen below:

>>> round(0.5)
0
>>> round(1.5)
2
>>> round(2.5)
2


I would think this is a common need, but I cannot find a function in
the Python library to do it. I wrote my own, but did I miss such a
method in my search of the Python library?

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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Diez B. Roggisch

Terry Reedy schrieb:



DaveM wrote:
On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" 
<[EMAIL PROTECTED]>

wrote:
As a rule of thumb, don't return objects you didn't create inside a 
function from scratch.


Unless its job is specifically to get/fetch an object (reference 
thereto) from someplace the caller cannot or should not access.  But 
then it should probably not mutate the object before returning the 
reference.


I maybe should paraphrase "don't return objects you passed as arguments 
from a function". Of course there are exceptions to this rule - but 
these are few, the canonical being chained function calls like this:



class Whatever(object):

   def do_something(self, arguments):
   
   return self



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


Re: Attack a sacred Python Cow

2008-07-27 Thread Bruno Desthuilliers

Derek Martin a écrit :

On Sun, Jul 27, 2008 at 08:19:17AM +, Steven D'Aprano wrote:

You take the name down to a single letter. As I suggested in an earlier
post on this thread, why not take it down to zero letters? 
The question isn't "why not", but "why". The status quo works well as it 
is, even if it isn't perfect. Prove that implicit self is a good idea -- 
or at least prove that it is an idea worth considering.


Come on, this sounds like a schoolyard argument.  This comes down to a
matter of style, and as such, is impossible to prove.  It's largely a
question of individual preference.

That said, the argument in favor is rather simple:

1. This is an extremely common idiom in Python
2. It is completely unnecessary, and the language does not suffer for
   making it implicit
3. Making it implicit reduces typing, reduces opportunities for
   mistakes, and arguably increases consistency.


"arguably", indeed, cf below.


As for the latter part of #3, self (or some other variable) is
required in the parameter list of object methods,


It's actually the parameter list of the *function* that is used as the 
implementation of a method. Not quite the same thing. And then, 
consistency mandates that the target object of the method is part of the 
parameter list of the *function*, since that's how you make objects 
availables to a function.



however when the
method is *called*, it is omitted.


Certainly not. You need to lookup the corresponding attribute *on a 
given object* to get the method. Whether you write


  some_object.some_method()

or

  some_function(some_object)

you still need to explicitely mention some_object.



It is implied, supplied by Python.


Neither. The target object is passed to the function by the method 
object, which is itself returned by the __get__ method of function 
objects, which is one possible application of the more general 
descriptor protocol (the same protocol that is used for computed 
attributes). IOW, there's nothing specific to 'methods' here, just the 
use of two general features (functions and the descriptor protocol). 
FWIW, you can write your own callable, and write it so it behave just 
like a function here:


import types

class MyCallable(object):
   def __call__(self, obj):
   print "calling %s with %s" % (self, obj)
   def __get__(self, instance, cls):
   return types.MethodType(self.__call__, instance, cls)

class Foo(object):
bar = MyCallable()

print Foo.bar
f = Foo()
f.bar()


Thus when an object method is called, it must be called with one fewer
arguments than those which are defined.   This can be confusing,
especially to new programmers.


This is confusing as long as you insist on saying that what you 
"def"ined is a method - which is not the case.



It can also be argued that it makes the code less ugly, though again,
that's a matter of preference.

It's not enough to show that a change "isn't bad" -- you have to show 
that it is actively good. 


But he did... he pointed out that *it saves work*, without actually
being bad.  Benefit, without drawback.  Sounds good to me!

"Don't need to look at the method signature" is not an argument in favour 
of implicit self. 


Yes, actually, it is.


It isn't, since there's no "method signature" to look at !-)


 If there is a well-defined feature of Python
which provides access to the object within itself,


The point is that you don't get access to the object "within itself". 
You get access to an object *within a function*.


The fact that a function is defined within a class statement doesn't 
imply any "magic", it just creates a function object, bind it to a name, 
and make that object an attribute of the class. You have the very same 
result by defining the function outside the class statement and binding 
it within the class statement, by defining the function outside the 
class and binding it to the class outside the class statement, by 
binding the name to a lambda within the class statement etc...



then the
opportunities for mistakes when someone decides to use something else
are lessened.


You don't need to look at the method signature when you're using an
explicit self either.


That isn't necessarily true.  If you're using someone else's code, and
they didn't use "self" -- or worse yet, if they chose this variable's
name randomly throughout their classes -- then you may well need to
look back to see what was used.

It's bad programming, but the world is full of bad programmers, and we
don't always have the choice not to use their code.  Isn't one of
Python's goals to minimize opportunities for bad programming?


Nope. That's Java's goal. Python's goals are to maximize opportunities 
for good programming, which is quite different.



Providing a keyword equivalent to self and removing the need to name
it in object methods is one way to do that.


It's also a way to make Python more complicated than it needs to be. At 
least with the current state, you define your functions 

Re: with statement for two files

2008-07-27 Thread Diez B. Roggisch

braver schrieb:

Can open two files in a with statement:

with open(src) as readin, open(dst,"w") as writin:   # WRONG: comma
doesn't work
  ...

-- so that you have transactional safety for two file descriptors?
The comma syntax doesn't work, but is there a way, except for

with open(src) as readin:
  with open(dst,"w) as writin:
...


I'm not aware of any pre-defined context manager which does that.
But you can write your own context manager to do that, even a 
generalized combinator for taking two managers and create one, like this:


with context_creator(open, [src], open, [dst, "w"]) as readin, writin:
 ...

A fundamental problem though would be that the semantics become 
difficult. If closing the "outer" file fails, it's impossible to 
"rollback" the inner one.


So I think it really is better to use the nested with, which makes it 
crystal clear that the inner block might succeed independently from the 
outer one.


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


Re: Autocompletion and Interactive Tables in a Python IDE

2008-07-27 Thread Fabio Zadrozny
> a) Intellisense (tells you what classes/methods are available and what
> variables go into a function)
> b) Code Completion (guesses your code after four letters)
> c) Data-Orientation; multiple data sessions can be open, data can be
> viewed easily
>
> Python's IDLE has only half of the first of these features.  I did a
> lot of searching and found the PyDev extensions for Eclipse's Python
> IDE, and found that they've got Intellisense.  I'm still missing b and
> c, and am getting extremely frustrated programming so slowly..


Hi Anthony,

Actually, Pydev (both open source and Pydev Extensions) provide 'a' and 'b'
-- if it's not showing to you, it may be that the pythonpath is not
correctly configured (see http://fabioz.com/pydev/manual_101_root.html for
instructions on how to configure it). As for 'c', I'm sure there's more than
one plugin that can give that to you within Eclipse (search google for
eclipse database plugins) -- I haven't used any of those, so, I can't really
comment on them.

Cheers,

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

Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Terry Reedy



DaveM wrote:

On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]>
wrote:
As a rule of thumb, don't return objects you didn't create inside a 
function from scratch.


Unless its job is specifically to get/fetch an object (reference 
thereto) from someplace the caller cannot or should not access.  But 
then it should probably not mutate the object before returning the 
reference.


I wish I'd had that advice when I started learning python. It would have
saved me no end of grief.


I wish I had seen this 'rule' before too.

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


with statement for two files

2008-07-27 Thread braver
Can open two files in a with statement:

with open(src) as readin, open(dst,"w") as writin:   # WRONG: comma
doesn't work
  ...

-- so that you have transactional safety for two file descriptors?
The comma syntax doesn't work, but is there a way, except for

with open(src) as readin:
  with open(dst,"w) as writin:
...

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Bruno Desthuilliers

Jordan a écrit :
(snip)

about Python Zen:


Perhaps we're just looking at an instance of a wider problem - smart
people boil good ideas down into short slogans, which are nice and
memorable and somewhat helpful, but can lead to bad consequences when
lots of others start overusing or misunderstanding them.


This is true for just each and every "golden rule" in programming - like 
"goto are evil", "globals are evil", "side effects are evil", "early 
returns are evil",  "public attributes are evil", etc... If you blindly 
apply any rule without understanding the rationales behind it, then 
you're into cargo-cult thinking. And once you understand the reasons 
that led someone to formulate such a rule, you just don't have to bother 
about it anymore - you just use your common sense to do what seems 
appropriate in a given situation.

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Bruno Desthuilliers

Lawrence D'Oliveiro a écrit :

In message
<[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:


"Support OO but it doesn't have to"? That sounds like saying that in
some Python implementations you'll be able to use OO, but that you
just might bump into a Python distribution ...


Change "distribution" to "program" and you're on the right track.


Since just everything that can be bound to a name is actually an object, 
I don't see how you could do anything in Python without using objects.


Now if what you meant is that nothing in Python forces you into 
designing your program the OO way, then Java is not an OOPL neither 
(never seen a Java program where you have classes with only static 
methods and classes with only public attributes - IOW, functions and 
structs ?).

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jul 26, 11:22 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:

Russ P. wrote:

On Jul 26, 2:25 pm, Terry Reedy

There is a lot of code you have not seen.  Really.  In informal code I
use 's' and 'o' for 'self' and 'other'.  I don't usually post such
because it is not considered polite.  So you have seen a biased sample
of the universe.

You take the name down to a single letter. As I suggested in an
earlier post on this thread, why not take it down to zero letters?

Because 1 letter is legal now, while no letters (already proposed and
rejected) is a major change and breakage of current simplicity and
consistency for zero functional benefit.


Sorry, but I fail to see how it is a "major change." It only applies
to the first argument of a class member function, 


There's nothing like a "class member function" in Python.

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Bruno Desthuilliers

Marcus.CM a écrit :
Well after reading some of these posts on "sacred python cow" on the 
"self" , i would generally feel that most programmers
who started with C++/Java would find it odd. And its true, i agree 
completely there should not be a need to put "self" into every single

member function.


"member function" is C++. The way Python works is that you defines 
functions (inside or outside a class, that doesn't matter) that, when 
set as *class* attributes, are used as the *implementation* of the 
corresponding method.


I think it's very important to use appropriate terms to understand 
what's really going on here. As soon as you understand that what you 
"def"ine is a *not* a method, but a *function* (eventually) used as the 
*implementation* of a method, the necessary declaration of the target 
object (instance or class) in the function's signature just makes sense 
 - the usual way to make some object accessible to the body of a 
function is to pass this object as argument, isn't it ?


(snip)


What could be done instead is :-

1. python should hardcode the keyword "self". So whenever this keyword 
is used, it would automatically implied that it is

referring to a class scope variable.


Usually, 'self' is used for *instance* attributes, you know. "class 
attribute" are attributes of the class object itself (that is, shared by 
all instances of the class).




This would be similar to how the 
"this" keyword is used in C++.


2. Omit self from the parameter.


Now how would it work for functions defined outside a class statement, 
but used as the implementation of a method ?


def toto(self):
   # dummy exemple code
   return self

class Tata(object):
   pass

Tata.tutu = toto

class Titi(object):
   tutu = toto

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Bruno Desthuilliers

Torsten Bronger a écrit :

Hallöchen!

Bruno Desthuilliers writes:


Torsten Bronger a écrit :


(snip)


One could surely find ways to realise this.  However, the design
goal should be: Make the frequent case simple, and the rare case
possible.

Given the (more and more prominent) use of decorators, metaclasses
and other meta-programming techniques in Python, I'm not sure the
cases where you really need access to Python's object model inners
are that "rare". Not in my code at least.


What does "not rare" mean for you?


More than once a week.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Colin J. Williams


Russ P. wrote:

On Jul 26, 2:25 pm, Terry Reedy

There is a lot of code you have not seen.  Really.  In informal code I
use 's' and 'o' for 'self' and 'other'.  I don't usually post such
because it is not considered polite.  So you have seen a biased sample
of the universe.


You take the name down to a single letter. As I suggested in an
earlier post on this thread, why not take it down to zero letters? You
could if Python accepted something like

class Whatever:

def fun( , cat):

.cat = cat

This is even better than the single-character name, not only because
it is shorter, but also because there is no question that you are
referring to "self." No need to look back at the method signature to
verify that.

For those who don't like the way the empty first argument looks, maybe
something like this could be allowed:

def fun( ., cat):


I don't see the need for the comma in fun.

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


Re: Confounded by Python objects

2008-07-27 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

On Sat, 26 Jul 2008 18:54:22 +, Robert Latest wrote:


Here's an interesting side note: After fixing my "Channel" thingy the
whole project behaved as expected. But there was an interesting hitch.
The main part revolves around another class, "Sequence", which has a
list of Channels as attribute. I was curious about the performance of my
script, because eventually this construct is supposed to handle
megabytes of data. So I wrote a simple loop that creates a new Sequence,
fills all the Channels with data, and repeats.

Interistingly, the first couple of dozens iterations went satisfactorily
quickly (took about 1 second total), but after a hundred or so times it
got really slow -- like a couple of seconds per iteration.

Playing around with the code, not really knowing what to do, I found
that in the "Sequence" class I had again erroneously declared a
class-level attribute -- rather harmlessly, just a string, that got
assigned to once in each iteration on object creation.

After I had deleted that, the loop went blindingly fast without slowing
down.

What's the mechanics behind this behavior?


Without actually seeing the code, it's difficult to be sure, but my guess 
is that you were accidentally doing repeated string concatenation. This 
can be very slow.


In general, anything that looks like this:

s = ''
for i in range(1):  # or any big number
s = s + 'another string'

can be slow. Very slow.


But this is way faster:

s = ''
for i in range(1):  # or any big number
s += 'another string'


(snip)

It's harder to stumble across the slow behaviour these days, as Python 
2.4 introduced an optimization that, under some circumstances, makes 
string concatenation almost as fast as using join().


yeps : using augmented assignment (s =+ some_string) instead of 
concatenation and rebinding (s = s + some_string).



But be warned: join()
is still the recommended approach. Don't count on this optimization to 
save you from slow code.

>
If you want to see just how slow repeated concatenation is compared to 
joining, try this:




import timeit
t1 = timeit.Timer('for i in xrange(1000): x=x+str(i)+"a"', 'x=""')
t2 = timeit.Timer('"".join(str(i)+"a" for i in xrange(1000))', '')

t1.repeat(number=30)

[0.8506159782409668, 0.80239105224609375, 0.73254203796386719]

t2.repeat(number=30)

[0.052678108215332031, 0.052067995071411133, 0.052803993225097656]

Concatenation is more than ten times slower in the example above,


Not using augmented assignment:

>>> from timeit import Timer
>>> t1 = Timer('for i in xrange(1000): x+= str(i)+"a"', 'x=""')
>>> t2 = Timer('"".join(str(i)+"a" for i in xrange(1000))', '')
>>> t1.repeat(number=30)
[0.07472991943359375, 0.064207077026367188, 0.064996957778930664]
>>> t2.repeat(number=30)
[0.071865081787109375, 0.061071872711181641, 0.06132817268371582]

(snip)


And even worse:


t1.repeat(number=50)

[2.7190279960632324, 2.6910948753356934, 2.7089321613311768]

t2.repeat(number=50)

[0.087616920471191406, 0.088094949722290039, 0.087819099426269531]



Not that worse here:

>>> t1.repeat(number=50)
[0.12305188179016113, 0.10764503479003906, 0.10605692863464355]
>>> t2.repeat(number=50)
[0.11200308799743652, 0.10315108299255371, 0.10278487205505371]
>>>

I'd still advise using the sep.join(seq) approach, but not because of 
performances.



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

Re: Attack a sacred Python Cow

2008-07-27 Thread Derek Martin
On Sun, Jul 27, 2008 at 08:19:17AM +, Steven D'Aprano wrote:
> > You take the name down to a single letter. As I suggested in an earlier
> > post on this thread, why not take it down to zero letters? 
> 
> The question isn't "why not", but "why". The status quo works well as it 
> is, even if it isn't perfect. Prove that implicit self is a good idea -- 
> or at least prove that it is an idea worth considering.

Come on, this sounds like a schoolyard argument.  This comes down to a
matter of style, and as such, is impossible to prove.  It's largely a
question of individual preference.

That said, the argument in favor is rather simple:

1. This is an extremely common idiom in Python
2. It is completely unnecessary, and the language does not suffer for
   making it implicit
3. Making it implicit reduces typing, reduces opportunities for
   mistakes, and arguably increases consistency.

As for the latter part of #3, self (or some other variable) is
required in the parameter list of object methods, however when the
method is *called*, it is omitted.  It is implied, supplied by Python.
Thus when an object method is called, it must be called with one fewer
arguments than those which are defined.  This can be confusing,
especially to new programmers.

It can also be argued that it makes the code less ugly, though again,
that's a matter of preference.

> It's not enough to show that a change "isn't bad" -- you have to show 
> that it is actively good. 

But he did... he pointed out that *it saves work*, without actually
being bad.  Benefit, without drawback.  Sounds good to me!

> "Don't need to look at the method signature" is not an argument in favour 
> of implicit self. 

Yes, actually, it is.  If there is a well-defined feature of Python
which provides access to the object within itself, then the
opportunities for mistakes when someone decides to use something else
are lessened.

> You don't need to look at the method signature when you're using an
> explicit self either.

That isn't necessarily true.  If you're using someone else's code, and
they didn't use "self" -- or worse yet, if they chose this variable's
name randomly throughout their classes -- then you may well need to
look back to see what was used.

It's bad programming, but the world is full of bad programmers, and we
don't always have the choice not to use their code.  Isn't one of
Python's goals to minimize opportunities for bad programming?
Providing a keyword equivalent to self and removing the need to name
it in object methods is one way to do that.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpBl0pdqGhaD.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Rant (was Re: x*x if x>10

2008-07-27 Thread DaveM
On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]>
wrote:


>As a rule of thumb, don't return objects you didn't create inside a 
>function from scratch.

I wish I'd had that advice when I started learning python. It would have
saved me no end of grief.

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 1:19 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote:

> > You take the name down to a single letter. As I suggested in an earlier
> > post on this thread, why not take it down to zero letters?
>
> The question isn't "why not", but "why". The status quo works well as it
> is, even if it isn't perfect. Prove that implicit self is a good idea --
> or at least prove that it is an idea worth considering.
>
> "I don't like typing self" doesn't convince me. The same argument could
> be made typing parentheses, colons, commas, etc. We could end up with
> something like this:
>
> class Foo base
> def method x y z
> .args = list x y z
>
> That's not necessarily wrong, but it's not Python.

And what does that have to do with my suggestion? Absolutely nothing.
It's a red herring that you seem to be using to obscure the fact that
you have no rational argument to make.

By the way, according to your "reasoning," Python 2.5 was *not* Python
when 2.1 was the latest version. But now it is! Yes, Python has
actually changed, yet remained Python. What a concept!

> It's not enough to show that a change "isn't bad" -- you have to show
> that it is actively good. Why should Python make any changes to the
> current explicit self without a clear and solid reason to change?
>
> > You could if Python accepted something like
>
> > class Whatever:
>
> > def fun( , cat):
>
> > .cat = cat
>
> > This is even better than the single-character name,
>
> By "better" do you mean "uglier"? If so, I agree with you. If not, then I
> disagree that it is better.

You seem to be freaked out by an empty argument. Actually, it bothers
me a bit too, which is why I suggested that a period could be used as
the first argument to indicate that, like Clint Eastwood in The Good,
the Bad, and the Ugly, "self" had no name here.

> > not only because it
> > is shorter, but also because there is no question that you are referring
> > to "self." No need to look back at the method signature to verify that.
>
> "Don't need to look at the method signature" is not an argument in favour
> of implicit self. You don't need to look at the method signature when
> you're using an explicit self either.

Actually, you do. The name "self" could be used for any argument -- or
even for a local variable. No good programmer would do such a thing,
of course, but not all programmers are good programmers (and not all
Python programmers read the stern admonitions against such practices
on this forum). And if you are reviewing critical code, you had darn
well better verify that "self" is the first argument. With my
proposal, you would not need to do that.

Is that a major advantage? No. But it is a minor advantage. And it is
perfectly logical.

Am I suggesting that unnamed first arguments should always be used?
No, of course not. But I am saying that in some cases it can unclutter
and simplify the code.

> What happens with class-methods? With the cls (or if you prefer klass)
> convention, it is simple to tell what object I am referring to. Now I
> have to go back to the method signature to see if it is a class method or
> instance method, instead of just looking at the explicit name.

Bt. Wrong again. The exact same convention could apply there. And
the same benefits apply: less clutter and no need to keep the name of
the first argument in your head when reading the code.

> > For those who don't like the way the empty first argument looks, maybe
> > something like this could be allowed:
>
> > def fun( ., cat):
>
> Even uglier than the first. Convince me there's a benefit.

Actually, I think it's elegant. And I'll bet that if Guido had
suggested it, you would think it was beautiful. Why force a name to be
used when none is needed? Think about lambda functions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread Derek Martin
On Sun, Jul 27, 2008 at 08:13:53AM +, Steven D'Aprano wrote:
> On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote:
> 
> > Well after reading some of these posts on "sacred python cow" on the
> > "self" , i would generally feel that most programmers who started with
> > C++/Java would find it odd. 
> 
> You know, there are some programmers who haven't started with C++ or Java.

Indeed, I'm one of them.  In fact, I've never written even a single
program in either language (except maybe hello world or the
equivalent), and still, I have always thought that explicitly naming
the class instance variable in the parameter list of the object's
methods was a wart (albeit a very minor one) in Python.  It's a waste
of typing.

> > And its true, i agree completely there should not be a need to put
> > "self" into every single member function. If you were writing an
> > application and one of your classes adds the same variable to each
> > of its member function you would do away with it too.
> 
> Would I?  How would I do that here?

You missed the point.  The variable "other" in your posted class is
not intended to always refer to the same *object*...  Whereas "self"
is and does, and that was what was meant.  In such a case, you'd
obviously convert the variable to a class property.

Regardless of how it's implementd, it's such a common idiom to use
self to refer to object instances within a class in Python that it
ought to be more automatic.  Personally, I kind of like the idea of
using @ and thinking of it more like an operator...  Kind of like
dereferencing a pointer, only with an implied pointer name.

class foo:
def __init__():
@.increment = 2

def bar(a)
return a + @.increment

I'm sure all the Pythonistas will hate this idea though... ;-)  To be
honest, it smacks a little of Perl's magic variables, which I actually
hate with a passion.  This is the only place in Python I'd consider
doing something like this.  

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpq0OmSJMzPS.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Rant (was Re: x*x if x>10

2008-07-27 Thread DaveM
On Sun, 27 Jul 2008 09:28:28 -0700, Gary Herron <[EMAIL PROTECTED]>
wrote:


>> a = list(set(itertools.chain(*sessexam.values(
>> a.sort() #As I write I'm wondering if I really need it sorted. Hmm...
>> return a

>Didn't someone already answer that.  List addition and sum() both do 
>what you want.
>
> >>> A = [1,2,3]
> >>> B = [4,5,6]
> >>> C = [7,8,9]
>
> >>> A+B+C
>[1, 2, 3, 4, 5, 6, 7, 8, 9]

True, although unsuitable for my circumstance.


> >>> sum([A,B,C], [])
>[1, 2, 3, 4, 5, 6, 7, 8, 9]

Ah. I had no luck with sum, but I hadn't realised it needed the "[]" term. I
must read about it again.

>It doesn't get any easier than that.

Not only that, but it's exactly what I was after - and fastest, too,
although speed isn't really an issue. Thank you.

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Derek Martin
On Sat, Jul 26, 2008 at 12:06:05AM -0400, Terry Reedy wrote:
> There is no requirement to have 'self' in the parameter list.  

But there is a requirement to have *something* which refers to the
object instance.  Why can't this be implicit with a keyword defined in
python to refer to it?

> So the proposal would have to be that the compiler scan the function 
> body and decide which dotted name prefix is the one to be implicitly 
> added.  Have fun writing the discovery algorithm.  

That's crazy talk.

> Or the proposal would have to be that 'self' is mandatory for all 
> programmers in all languages.  I think *that* would be pernicious. 
> People are now free to write the more compact 's.sum = s.a + s.b + s.c' 

s = self

There, your problem is fixed.  Besides, in general, it's better
programming practie to use meaningful names, with fairly obvious and
well-understood exceptions.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpEV6qhBweow.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Attack a sacred Python Cow

2008-07-27 Thread Russ P.
On Jul 27, 3:11 am, alex23 <[EMAIL PROTECTED]> wrote:
> On Jul 27, 4:26 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
>
> > On Jul 26, 11:18 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> > > The use of '.' has been suggested before and rejected.
>
> > Where and why?
>
> Google is your 
> friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html

What Guido rejected there is most certainly *not*
what I suggested. I agree with Guido on that one.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Anders J. Munch

Gary Herron wrote:

 >>> A = [1,2,3]
 >>> B = [4,5,6]
 >>> C = [7,8,9]

 >>> A+B+C
[1, 2, 3, 4, 5, 6, 7, 8, 9]

 >>> sum([A,B,C], [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]


Careful now, this can be very slow.  sum uses __add__, not __iadd__, which gives 
this approach quadratic worst-case runtime.


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


Re: Questions on 64 bit versions of Python

2008-07-27 Thread Martin v. Löwis
> - AMD64 (or x86-64 or x64 or EMT64 or Intel64) is a 64-bit instruction
> set from AMD which is an extension to the i386 instruction set, and runs
> 32-bit (and 16-bit) i386-code natively. But, and this is important,
> despite the name the instruction set is also used by Intel (though they
> call it EMT64 and made a few minor changes).

Indeed, there are (unfortunately) many names for the architecture.
Originally, AMD called it x86-64, and later renamed it to AMD64. Intel
originally implemented it under the name EM64T (for Extended Memory 64
Technology), and now calls the architecture Intel 64.

Microsoft (apparently not wanting to take sides) calls it x64.

I personally believe that whoever invents a technology also
gets to name it, so I encourage use of the name AMD gives it
(which is AMD64). That's why the Python installer has that label
in its name.

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


method decorators and more on decorators

2008-07-27 Thread Themistoklis Bourdenas
Hi, is there any possible way to get the class or class name inside a method
decorator? For example in the code sample below:

def decorate(func):
  print type(func)
  return func

class myclass:

  @decorate
  def foo(self):
pass

The output of this program will be the type of the supplied func in
decorate, i.e. method foo. However, the type is function foo, a free
function, not an instance method myclass.foo.

On a related note, as the actual instance method of myclass is not foo but
decorate(foo), why are they called method decorators? This does not decorate
methods, they decorate functions and eventually the decorated functions
become methods. The name method decorator sounds a bit misleading to me.

So returning to my original question is there any way I can get the class
inside decorate()? I guess there is not, but just asking to make sure.

Speaking of decorators I'd also like to ask on the pending class decorators
that should be coming in a following version of the language. Are they going
to be in 2.6 or just 3.0? In the following example:

def class_decorate(cls):
  print 'class_decorate'
  return cls

def decorate(func):
  print 'decorate'
  return func

@class_decorate
class myclass:

  @decorate
  def foo(self):
pass

what will be the correct output?

class_decorate
decorate

or

decorate
class_decorate

In essence what is the order of application of class decorators compared to
the function decorators of their methods? I couldn't find any mention of
that issue in any of the PEPs. I guess it would be the latter, following the
behavior of metaclasses, but better be certain than speculate :)

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

Re: Attack a sacred Python Cow

2008-07-27 Thread castironpi
On Jul 26, 4:08 am, Nikolaus Rath <[EMAIL PROTECTED]> wrote:
> Terry Reedy <[EMAIL PROTECTED]> writes:
> > Nikolaus Rath wrote:
> >> Terry Reedy <[EMAIL PROTECTED]> writes:
> >>> Torsten Bronger wrote:
>  Hallöchen!
> >>>  > And why does this make the implicit insertion of "self" difficult?
>  I could easily write a preprocessor which does it after all.
> >>> class C():
> >>>   def f():
> >>>     a = 3
>
> >>> Inserting self into the arg list is trivial.  Mindlessly deciding
> >>> correctly whether or not to insert 'self.' before 'a' is impossible
> >>> when 'a' could ambiguously be either an attribute of self or a local
> >>> variable of f.  Or do you and/or Jordan plan to abolish local
> >>> variables for methods?
>
> >> Why do you think that 'self' should be inserted anywhere except in the
> >> arg list? AFAIU, the idea is to remove the need to write 'self' in the
> >> arg list, not to get rid of it entirely.
>
> > Because you must prefix self attributes with 'self.'. If you do not
> > use any attributes of the instance of the class you are making the
> > function an instance method of, then it is not really an instance
> > method and need not and I would say should not be masqueraded as
> > one. If the function is a static method, then it should be labeled
> > as one and no 'self' is not needed and auto insertion would be a
> > mistake. In brief, I assume the OP wants 'self' inserted in the body
> > because inserting it only in the parameter list and never using it
> > in the body is either silly or wrong.
>
> I think you misunderstood him. What he wants is to write
>
> class foo:
>    def bar(arg):
>        self.whatever = arg + 1
>
> instead of
>
> class foo:
>    def bar(self, arg)
>        self.whatever = arg + 1
>
> so 'self' should *automatically* only be inserted in the function
> declaration, and *manually* be typed for attributes.
>
> Best,
>
>    -Nikolaus
>
> --
>  »It is not worth an intelligent man's time to be in the majority.
>   By definition, there are already enough people to do that.«
>                                                          -J.H. Hardy

There's a further advantage:

class A:
  def get_auxclass( self, b, c ):
class B:
  def auxmeth( self2, d, e ):
#here, ...
return B

Because Python permits you to name 'the current instance' any name you
want, you're able to hold more than one current instance at one time.
In this case, you could write 'return self.val+ self2.val' with no
trouble, while I'm not even sure that anything like that is possible
in C, C++, Java, or anything higher other than Python.  (This is a
good point, outside of the usual, by the way.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-27 Thread castironpi
On Jul 27, 2:56 am, Nikolaus Rath <[EMAIL PROTECTED]> wrote:
> Terry Reedy <[EMAIL PROTECTED]> writes:
> >> What he wants is to write
>
> >  > class foo:
> >>    def bar(arg):
> >>        self.whatever = arg + 1
>
> >> instead of
>
> >> class foo:
> >>    def bar(self, arg)
> >>        self.whatever = arg + 1
>
> >> so 'self' should *automatically* only be inserted in the function
> >> declaration, and *manually* be typed for attributes.
>
> > which means making 'self' a keyword just so it can be omitted. Silly
> > and pernicious.
>
> Well, I guess that's more a matter of personal preference. I would go
> for it immediately (and also try rename it to '@' at the same time).
>
> Best,
>
>    -Nikolaus
>
> --


>  »It is not worth an intelligent man's time to be in the majority.
>   By definition, there are already enough people to do that.«
>                                                          -J.H. Hardy

Hardy has an interesting claim.  OT.

He has omitted a couple of lemmas, which aren't true.

1: There are enough people to be in the majority.
2: It is not worthwhile to be in the majority.
3: There is no majority of worthwhile timespending.
4: There is no majority of intelligent men.
5: Being in the majority takes time.

It is worth some intelligent men's time to be in the majority; the
majority of intelligent men are intelligent men, and are in the
majority of intelligent men.  Perhaps it is merely not worth their
time to be.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Terry Reedy

DaveM wrote:

On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]>



You'll have guessed, I'm sure, that I'm not a professional programmer. This
was the third rewrite of a program to match candidate groups to examiners on
a three day course I run, necessitated on this occasion by a change in the
structure of the course. I originally learnt python as I wrote, and some of
the early code was ugly and verbose, so once the current rewrite was working
I took the opportunity to tidy the code up and document it (yes, I know, but
as I said, I'm an amateur). The list concatenation was an itch I couldn't
scratch:

temp = []
for value in sessexam.values():
temp.extend(value)
c_exam = [name for name in set(temp)] #See what I mean about verbose?
c_exam.sort()
return c_exam

Six lines just didn't feel like it ought to be the best way to do something
so simple. I liked the attempt below better, but was foolish enough to time
it, so that was the end of that.

return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values()

The current version (below) is a compromise, but I still feel there _ought_
to be a simple one word command to join multiple lists.


There is, as others have posted, but if you are going to dump the lists 
into a set, there is no need to concatenate them together first, and it 
is better not to.  Just dump them directly into set.


a = list(set(itertools.chain(*sessexam.values(


This is a pretty good way of skipping the intermediate long list.  Another:

a = set()
for l in sessexam.values():
  a.update(set(l))

If course, if sessexam.values() does not need to be ordered and returns 
sets instead, the set call in not needed.



a.sort() #As I write I'm wondering if I really need it sorted. Hmm...
return a


If you want all in one line...
  return sorted(set(itertools.chain(*sessexam.values(

There is no virtue to calling list then .sort, since that is what sorted 
basically does.


def sorted(iterable):
  tem = list(iterable)
  tem.sort()
  return tem

tjr


tjr

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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Diez B. Roggisch


Can you tell us what you mean by "several names of one object"? You mean 
this?


a = range(10)
b = a

id(a) == id(b)


? Passing references instead of values is an extremely important concept 
of many languages, without it you would end up copying most of the time.


OK. I've obviously been thinking about things the wrong way. In Forth you
pass the memory address around, and presumably that's essentially what's
happening when you pass a reference.


Pretty much, yes. And I for once can say that I've been caught by 
modifying e.g. stack-locals instead of heap-objects in C++ by accident.




The problem is, I get caught frequently
in this situation:

a = [1,2,3]

def foo(x):
do_something_with_x
return x

...

Then when I call foo(a), a gets changed. It just isn't the effect I expect
from changing a local.


It's the way things work - mutables are mutables. If you want them to be 
modified, use the module copy.


As a rule of thumb, don't return objects you didn't create inside a 
function from scratch.


Which is the exact reasoning for the

list.sort

method btw - returning None is supposed to make you aware of the 
in-place modification.





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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread DaveM
On Sun, 27 Jul 2008 16:41:19 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]>
wrote:


>You obviously aren't aware of the pitfalls regarding the mis-use of or 
>and and for this usage.



Well, yes, I am (and the way around the problem), but as its never caught me
out (so far), I hadn't considered it. 

>Can you tell us what you mean by "several names of one object"? You mean 
>this?
>
>a = range(10)
>b = a
>
>id(a) == id(b)
>
>
>? Passing references instead of values is an extremely important concept 
>of many languages, without it you would end up copying most of the time.

OK. I've obviously been thinking about things the wrong way. In Forth you
pass the memory address around, and presumably that's essentially what's
happening when you pass a reference. The problem is, I get caught frequently
in this situation:

a = [1,2,3]

def foo(x):
do_something_with_x
return x

...

Then when I call foo(a), a gets changed. It just isn't the effect I expect
from changing a local.

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Terry Reedy



Steven D'Aprano wrote:

On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote:


Well after reading some of these posts on "sacred python cow" on the
"self" , i would generally feel that most programmers who started with
C++/Java would find it odd. 


You know, there are some programmers who haven't started with C++ or Java.


Like my teenager, who is only 1 of many kids learning Python as a first 
algorithm language.  If not now, eventually, I expect a majority of 
Python programmers to *not* be C++/Java graduates.


tjr

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


Re: Attack a sacred Python Cow

2008-07-27 Thread Marc 'BlackJack' Rintsch
On Sat, 26 Jul 2008 21:46:31 -0700, s0suk3 wrote:

> (It's true that C++ has more OO features than Python, like private/
> public members, virtual methods, etc.

Oh yeah, again the discussion about `private`/`public` and if that's an 
important OOP feature.  :-)

Aren't *all* methods in Python "virtual"?

And what's "etc."?

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


Google Group: architectgurus

2008-07-27 Thread Sudhakar Chavali
Hi



I have created a group called architectgurus (http://groups.google.com/
group/architectgurus) or [EMAIL PROTECTED] .
Irrespective of technology, vendor, domain I will be discussing and
share my thoughts in homogenous and harmonious way. If you are
interested even you can join and contribute your thoughts in this
group. My intention doing these activities is to spread the knowledge
and thoughts across the globe.



Best Regards
Sudhakar Chavali
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Diez B. Roggisch

DaveM schrieb:

On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]>
wrote:


Marc 'BlackJack' Rintsch schrieb:

On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote:


DaveM schrieb:
Getting back to the list concatenation, I finally found the itertools.chain 
command which is the most compact and fastest (or second fastest by a 
trivial amount, I can't remember which). Along the way, I must have 
tried/used half a dozen methods, ...which brings me back my initial PERL 
comment. There's more than one way to do it in Python, too.



But I *do* know that taking the python zen literally is fruitless.


I think it should be taken more literally than the wrong reduction to 
"there should be only one way".  People tend to forget "obvious" and 
"preferably" all the time.


Good point. The OP found the obvious way of extending. I wonder what his 
reasons were to abandon it.


You'll have guessed, I'm sure, that I'm not a professional programmer. This
was the third rewrite of a program to match candidate groups to examiners on
a three day course I run, necessitated on this occasion by a change in the
structure of the course. I originally learnt python as I wrote, and some of
the early code was ugly and verbose, so once the current rewrite was working
I took the opportunity to tidy the code up and document it (yes, I know, but
as I said, I'm an amateur). The list concatenation was an itch I couldn't
scratch:

temp = []
for value in sessexam.values():
temp.extend(value)
c_exam = [name for name in set(temp)] #See what I mean about verbose?
c_exam.sort()
return c_exam

Six lines just didn't feel like it ought to be the best way to do something
so simple. I liked the attempt below better, but was foolish enough to time
it, so that was the end of that.

return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values()

The current version (below) is a compromise, but I still feel there _ought_
to be a simple one word command to join multiple lists.

a = list(set(itertools.chain(*sessexam.values(
a.sort() #As I write I'm wondering if I really need it sorted. Hmm...
return a


You are aware that the above is much more than "concatenate a bunch of 
lists?" You want unique values & sorting, which are two additional 
requirements. I'd say 3 lines of code for three requirements is ok, so


all = sum(sessexam.values(), [])
unique = set(all)
sorted_result = sorted(unique)

And obviously there are more ways to skin *that* cat, some (as 
itertools.chain) being less memory intensive:



a = sorted(set(itertools.chain(*sessexam.values(

It's debatable if this one-liner is really the way to go, but I fail to 
see how you expect there to be a specialized builtin for this kind of task.



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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Gary Herron

DaveM wrote:

On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]>
wrote:

  

Marc 'BlackJack' Rintsch schrieb:


On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote:

  

DaveM schrieb:

Getting back to the list concatenation, I finally found the itertools.chain 
command which is the most compact and fastest (or second fastest by a 
trivial amount, I can't remember which). Along the way, I must have 
tried/used half a dozen methods, ...which brings me back my initial PERL 
comment. There's more than one way to do it in Python, too.
  


  

But I *do* know that taking the python zen literally is fruitless.



  
I think it should be taken more literally than the wrong reduction to 
"there should be only one way".  People tend to forget "obvious" and 
"preferably" all the time.
  


  
Good point. The OP found the obvious way of extending. I wonder what his 
reasons were to abandon it.



You'll have guessed, I'm sure, that I'm not a professional programmer. This
was the third rewrite of a program to match candidate groups to examiners on
a three day course I run, necessitated on this occasion by a change in the
structure of the course. I originally learnt python as I wrote, and some of
the early code was ugly and verbose, so once the current rewrite was working
I took the opportunity to tidy the code up and document it (yes, I know, but
as I said, I'm an amateur). The list concatenation was an itch I couldn't
scratch:

temp = []
for value in sessexam.values():
temp.extend(value)
c_exam = [name for name in set(temp)] #See what I mean about verbose?
c_exam.sort()
return c_exam

Six lines just didn't feel like it ought to be the best way to do something
so simple. I liked the attempt below better, but was foolish enough to time
it, so that was the end of that.

return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values()

The current version (below) is a compromise, but I still feel there _ought_
to be a simple one word command to join multiple lists.

a = list(set(itertools.chain(*sessexam.values(
a.sort() #As I write I'm wondering if I really need it sorted. Hmm...
return a
  


Didn't someone already answer that.  List addition and sum() both do 
what you want.


>>> A = [1,2,3]
>>> B = [4,5,6]
>>> C = [7,8,9]

>>> A+B+C
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> sum([A,B,C], [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

It doesn't get any easier than that.

Gary Herron




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


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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread DaveM
On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]>
wrote:

>Marc 'BlackJack' Rintsch schrieb:
>> On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote:
>> 
>>> DaveM schrieb:
 Getting back to the list concatenation, I finally found the 
 itertools.chain 
 command which is the most compact and fastest (or second fastest by a 
 trivial amount, I can't remember which). Along the way, I must have 
 tried/used half a dozen methods, ...which brings me back my initial PERL 
 comment. There's more than one way to do it in Python, too.

>>> But I *do* know that taking the python zen literally is fruitless.

>> I think it should be taken more literally than the wrong reduction to 
>> "there should be only one way".  People tend to forget "obvious" and 
>> "preferably" all the time.

>Good point. The OP found the obvious way of extending. I wonder what his 
>reasons were to abandon it.

You'll have guessed, I'm sure, that I'm not a professional programmer. This
was the third rewrite of a program to match candidate groups to examiners on
a three day course I run, necessitated on this occasion by a change in the
structure of the course. I originally learnt python as I wrote, and some of
the early code was ugly and verbose, so once the current rewrite was working
I took the opportunity to tidy the code up and document it (yes, I know, but
as I said, I'm an amateur). The list concatenation was an itch I couldn't
scratch:

temp = []
for value in sessexam.values():
temp.extend(value)
c_exam = [name for name in set(temp)] #See what I mean about verbose?
c_exam.sort()
return c_exam

Six lines just didn't feel like it ought to be the best way to do something
so simple. I liked the attempt below better, but was foolish enough to time
it, so that was the end of that.

return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values()

The current version (below) is a compromise, but I still feel there _ought_
to be a simple one word command to join multiple lists.

a = list(set(itertools.chain(*sessexam.values(
a.sort() #As I write I'm wondering if I really need it sorted. Hmm...
return a

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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread alex23
On Jul 28, 1:26 am, ssecorp <[EMAIL PROTECTED]> wrote:
> I might be misunderstanding OP but:
>
> a+b+c+d+e is simple way of concatenating 5 lists...
>
> as a function that takes any amount of lists and concatenates them:
> def concat(*args):
> c = []
> for elem in args:
> c += elem
> return c
>
> don't know if extend is faster or slower or the same as + :
>
> def concat(*args):
> c = []
> for elem in args:
> c.extend(elem)
> return c
>
> I don't know of a built-in.

Just to infuriate the OP even further, here's the list comprehension
version :)

>>> def concat(*args):
... return [elem for arg in args for elem in arg]

Hope this helps!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating through 2 files simultaneously

2008-07-27 Thread glman74
>
> So import STDOUT and make stderr=STDOUT in the Popen call, you will then
> have one file/pipe to deal with p1.stdout.

Thank you - that works great!

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


Re: Insert string into string

2008-07-27 Thread Mensanator
On Jul 27, 1:41�am, Peter Otten <[EMAIL PROTECTED]> wrote:
> Mensanator wrote:
> > I don't know why you're using stdin if you're reading from a file.
>
> From Francesco's initial post in his previous thread I inferred that he had
> a script like
>
> f = open("xxx.pdb")
> for line in f:
> � � # process line
> � � print line
>
> and was calling it
>
> python script.py >outfile
>
> My hope was that
>
> import sys
> for line in sys.stdin:
> � � # process line
> � � sys.stdout.write(line)
>
> invoked as
>
> python script.py outfile
>
> would be an improvement as it avoids hardcoding the filename, but instead
> chaos ensued...
>
> Francesco: Mensanator's script looks like you can take it "as is".

Well, I didn't bother to insert the serial number
into the extra line as the extra line wasn't given.
Hopefully, it's obvious how to do that.

> If you
> want to use Python to do other interesting things I highly recommend that
> you work your way through a tutorial of your choice. This will make
> subsequent trial-and-error much more fun.
>
> Following Roy's suggestion I also had a brief look at Biopython's PDB parser
> which has the advantage that it "understands" the file format.
> Unfortunately it is probably too complex for you to use at this point of
> your career as a pythonista ;)
>
> By the way, are you trying to modify the chain ID? Biopython locates that at
> position 21, so take this as a reminder that indices in Python start at 0,
> i. e. line[21] gives you the 22nd character in the line.
>
> Peter

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

Re: Rant (was Re: x*x if x>10

2008-07-27 Thread ssecorp
I might be misunderstanding OP but:

a+b+c+d+e is simple way of concatenating 5 lists...

as a function that takes any amount of lists and concatenates them:
def concat(*args):
c = []
for elem in args:
c += elem
return c

don't know if extend is faster or slower or the same as + :

def concat(*args):
c = []
for elem in args:
c.extend(elem)
return c

I don't know of a built-in.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Diez B. Roggisch

Marc 'BlackJack' Rintsch schrieb:

On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote:


DaveM schrieb:

Getting back to the
list concatenation, I finally found the itertools.chain command which
is the most compact and fastest (or second fastest by a trivial amount,
I can't remember which). Along the way, I must have tried/used half a
dozen methods, ...which brings me back my initial PERL comment. There's
more than one way to do it in Python, too.

Any non-trivial task has that property. I don't know enough perl to have
an example ready that shows something that python has only one way of
doing and perl has several.

But I *do* know that taking the python zen literally is fruitless.


I think it should be taken more literally than the wrong reduction to 
"there should be only one way".  People tend to forget "obvious" and 
"preferably" all the time.


Good point. The OP found the obvious way of extending. I wonder what his 
reasons were to abandon it.



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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote:

> DaveM schrieb:
>> Getting back to the
>> list concatenation, I finally found the itertools.chain command which
>> is the most compact and fastest (or second fastest by a trivial amount,
>> I can't remember which). Along the way, I must have tried/used half a
>> dozen methods, ...which brings me back my initial PERL comment. There's
>> more than one way to do it in Python, too.
> 
> Any non-trivial task has that property. I don't know enough perl to have
> an example ready that shows something that python has only one way of
> doing and perl has several.
> 
> But I *do* know that taking the python zen literally is fruitless.

I think it should be taken more literally than the wrong reduction to 
"there should be only one way".  People tend to forget "obvious" and 
"preferably" all the time.

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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Gary Herron

DaveM wrote:

On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 <[EMAIL PROTECTED]> wrote:

  

On Jul 27, 10:13 pm, ssecorp <[EMAIL PROTECTED]> wrote:


I have seen somewhere that you can write something like:
  


  

x*x if x>10
but exactly that doesn't work and I can't get any variation to work.
  


  

It's called a ternary operator. The format is:
 =  if  else 



I've seen the PERL saying/motto/boast, "There's more than one way to do it"
derided on more than one occasion on this group so what's the reason for
this additional way to put an if else statement on one line? Are "and" and
"or" constructions to produce the same effect not supported for this use?
  


The "and" and "or" construct which is equivalent to the ternary operator 
is quite convoluted and looks nothing like a conditional computation:

  (C and [A] or [B])[0]
This is inefficient, and nearly unreadable, which makes the highly 
useful ternary operator worthy of a syntactical construct.



The [A], [B] and [0] parts are absolutely necessary in the general case 
where A can have values that Python would consider equivalent to False.  
If you know A will never be equivalent to False then  you can use just this:

   C and A or B

Gary Herron



And while I'm on my high horse, I'd like to bring up list concatenations. I
recently needed to concatenate 5 lists, which doesn't sound a particularly
rare requirement to me. My first attempt was a straightforward loop
extending an empty list. That worked fine but looked like an awful bulky
solution. Afterwards I tried various formulae using "reduce" , falling foul
of the "=" catch on one occasion. Now I'm not a professional programmer, so
there may be good reasons for a single object to have multiple names in a
program, but it sounds like a recipe for disaster to me. Getting back to the
list concatenation, I finally found the itertools.chain command which is the
most compact and fastest (or second fastest by a trivial amount, I can't
remember which). Along the way, I must have tried/used half a dozen methods,
...which brings me back my initial PERL comment. There's more than one way
to do it in Python, too.

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


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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Diez B. Roggisch

DaveM schrieb:

On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 <[EMAIL PROTECTED]> wrote:


On Jul 27, 10:13 pm, ssecorp <[EMAIL PROTECTED]> wrote:

I have seen somewhere that you can write something like:



x*x if x>10
but exactly that doesn't work and I can't get any variation to work.



It's called a ternary operator. The format is:
 =  if  else 


I've seen the PERL saying/motto/boast, "There's more than one way to do it"
derided on more than one occasion on this group so what's the reason for
this additional way to put an if else statement on one line? Are "and" and
"or" constructions to produce the same effect not supported for this use?


You obviously aren't aware of the pitfalls regarding the mis-use of or 
and and for this usage.


Try this:

>>> a = True
>>> b = 1
>>> c = 2
>>> a and b or c
1
>>> a = False
>>> a and b or c
2
>>> a = True
>>> b = None
>>> a and b or c
2
>>>




Afterwards I tried various formulae using "reduce" , falling foul
of the "=" catch on one occasion. Now I'm not a professional programmer, so
there may be good reasons for a single object to have multiple names in a
program, but it sounds like a recipe for disaster to me.



Can you tell us what you mean by "several names of one object"? You mean 
this?


a = range(10)
b = a

id(a) == id(b)


? Passing references instead of values is an extremely important concept 
of many languages, without it you would end up copying most of the time.




Getting back to the
list concatenation, I finally found the itertools.chain command which is the
most compact and fastest (or second fastest by a trivial amount, I can't
remember which). Along the way, I must have tried/used half a dozen methods,
...which brings me back my initial PERL comment. There's more than one way
to do it in Python, too.


Any non-trivial task has that property. I don't know enough perl to have 
an example ready that shows something that python has only one way of 
doing and perl has several.


But I *do* know that taking the python zen literally is fruitless.


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


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread Karen Tracey
On Sun, Jul 27, 2008 at 10:17 AM, DaveM <[EMAIL PROTECTED]> wrote:

> On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 <[EMAIL PROTECTED]>
> wrote:
>
> >On Jul 27, 10:13 pm, ssecorp <[EMAIL PROTECTED]> wrote:
> >> I have seen somewhere that you can write something like:
>
> >> x*x if x>10
> >> but exactly that doesn't work and I can't get any variation to work.
>
> >It's called a ternary operator. The format is:
> > =  if  else 
>
> I've seen the PERL saying/motto/boast, "There's more than one way to do it"
> derided on more than one occasion on this group so what's the reason for
> this additional way to put an if else statement on one line? Are "and" and
> "or" constructions to produce the same effect not supported for this use?
>

In fact the PEP for this construct states:

The motivating use case was the prevalance of error-prone attempts
to achieve the same effect using "and" and "or".

See: http://www.python.org/dev/peps/pep-0308/

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

Rant (was Re: x*x if x>10

2008-07-27 Thread DaveM
On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 <[EMAIL PROTECTED]> wrote:

>On Jul 27, 10:13 pm, ssecorp <[EMAIL PROTECTED]> wrote:
>> I have seen somewhere that you can write something like:

>> x*x if x>10
>> but exactly that doesn't work and I can't get any variation to work.

>It's called a ternary operator. The format is:
> =  if  else 

I've seen the PERL saying/motto/boast, "There's more than one way to do it"
derided on more than one occasion on this group so what's the reason for
this additional way to put an if else statement on one line? Are "and" and
"or" constructions to produce the same effect not supported for this use?

And while I'm on my high horse, I'd like to bring up list concatenations. I
recently needed to concatenate 5 lists, which doesn't sound a particularly
rare requirement to me. My first attempt was a straightforward loop
extending an empty list. That worked fine but looked like an awful bulky
solution. Afterwards I tried various formulae using "reduce" , falling foul
of the "=" catch on one occasion. Now I'm not a professional programmer, so
there may be good reasons for a single object to have multiple names in a
program, but it sounds like a recipe for disaster to me. Getting back to the
list concatenation, I finally found the itertools.chain command which is the
most compact and fastest (or second fastest by a trivial amount, I can't
remember which). Along the way, I must have tried/used half a dozen methods,
...which brings me back my initial PERL comment. There's more than one way
to do it in Python, too.

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


Re: Read .txt file like .py file

2008-07-27 Thread Stefan Behnel
King wrote:
> I have a text file and contents are:
> 
> Help="""
> Code is written by xteam.
> """
> value = 0.0
> 
> 
> How do I read this file like python syntax. What I mean is first
> readline operation should return complete declaration of 'Help'
> variable. If I evaluate this string then it should create a 'Help'
> variable with it's value.

If you trust the author of the file and you're sure the code in the text file
isn't an Internet worm and won't delete all your files, you can get away with
the built-in "execfile" function.

If you want more security, look at the compiler module and the ast module.
They allow you to parse the file like a normal Python source file, and IIRC,
there are also ways to execute single statements from a syntax tree.

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


Re: xml.dom's weirdness?

2008-07-27 Thread Stefan Behnel
Lie wrote:
> I'm more concerned about the number of modules imported by making an
> error (from 30 on the startup to 187) and the side-effect of making an
> error, which makes modules such as xml.*/email.* that previously
> doesn't exist get imported out of the blue...

Using my system Python (2.5.1 on Ubunutu Gutsy):

  $ strace -e open python -c '' 2>&1 | wc -l
  551
  $ strace -e open python -c '<><<' 2>&1 | wc -l
  4631

Using a self-built Python I have lying around:

  $ strace -e open python2.3 -c '' 2>&1 | wc -l
  210
  $ strace -e open python2.3 -c '<><<' 2>&1 | wc -l
  214

  $ strace -e open python2.6 -c '' 2>&1 | wc -l
  138
  $ strace -e open python2.6 -c '<><<' 2>&1 | wc -l
  142

Blame Ubuntu/Debian.

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


Read .txt file like .py file

2008-07-27 Thread King
I have a text file and contents are:

Help="""
Code is written by xteam.
"""
value = 0.0


How do I read this file like python syntax. What I mean is first
readline operation should return complete declaration of 'Help'
variable. If I evaluate this string then it should create a 'Help'
variable with it's value.

May be something related to 'parsing' would help but I don't know much.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating through 2 files simultaneously

2008-07-27 Thread Rob Williscroft
 wrote in news:7ae96aff-c1a7-4763-8db7-
[EMAIL PROTECTED] in comp.lang.python:

> Hi folks,
> 
> I am trying to tee off both stdout and stderr from a process run
> through Popen.
> As a test, I am first trying to print the output below:
> 
> from subprocess import Popen,PIPE
> ...
> p1 = Popen(['cvs', 'update'], stdout=PIPE, stderr=PIPE)
> for (l1, l2) in zip(p1.stdout, p1.stderr):
> print '-->' + l1,
> print '-->' + l2,
> 
> This doesn't work - probably because I cannot iterate through the
> pipes this way.
> 
> I am new to Python, and I'd appreciate it if you could please explain
> why this
> doesn't work and/or suggest an alternate way to redirect stdout and
> stderr to a
> common place.
> 
> My objective is for my code to print out stdout/stderr messages and at
> the same
> time redirect them to a log file.

>From the manual http://docs.python.org/lib/node528.html>:

stdin, stdout and stderr specify ... 
... Additionally, stderr can be STDOUT, which indicates that the stderr 
data from the applications should be captured into the same file handle 
as for stdout. 

So import STDOUT and make stderr=STDOUT in the Popen call, you will then
have one file/pipe to deal with p1.stdout.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >