Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'

2005-07-12 Thread Peter Otten
Ric Da Force wrote:

> I have a string such as 'C1, C2, C3'.   Without assuming that each bit of
> text is of fixed size, what is the easiest way to change this list so that
> it reads:
> 'C1, C2 and C3' regardless of the length of the string.

>>> " and".join("C1, C2, C3".rsplit(",", 1))
'C1, C2 and C3'

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


Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'

2005-07-12 Thread Christoph Rackwitz
foo = "C1, C2, C3"
foo = foo.split(", ") # ['C1', 'C2', 'C3']
foo = ", ".join(foo[:-1]) + " and " + foo[-1] # just slicing and
joining it

you can always look for something here:
http://docs.python.org/lib/lib.html
and there:
http://docs.python.org/ref/

if you want to know, what methods an object has, try this (i shortened
the output a bit):
>>> foo = "C1, C2, C3"
>>> dir(foo)
['__add__', '__doc__', ..., 'capitalize', 'center', 'count',
'decode','encode', 'endswith', 'expandtabs', 'find', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind',
'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']
>>>

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


Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'

2005-07-12 Thread Brian van den Broek
Ric Da Force said unto the world upon 12/07/2005 02:43:
> Hi,
> 
> I have a string such as 'C1, C2, C3'.   Without assuming that each bit of 
> text is of fixed size, what is the easiest way to change this list so that 
> it reads:
> 'C1, C2 and C3' regardless of the length of the string.
> 
> Regards and sorry for the newbie question,
> 
> Ric 
> 

Hi Ric,

the rsplit method of strings should get you going:

 >>> data = "the first bit, then the second, finally the third"
 >>> chunks = data.rsplit(',', 1)
 >>> chunks
['the first bit, then the second', ' finally the third']
 >>>

Best,

Brian vdB


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


Re: __eq__ on a dict

2005-07-12 Thread Aaron Bingham
Hi Steven,

Thanks for digging into this.

"Steven D'Aprano" <[EMAIL PROTECTED]> writes:

> Replying to myself... how sad.
>
> On Tue, 12 Jul 2005 15:41:46 +1000, Steven D'Aprano wrote:
>
>> That wasn't clear from his post at all. If he had explained what he
>> wanted, I wouldn't have wasted my time explaining what he already knew.
>
> On reading it, that came across more snarky than I intended. Sorry.

It's ok.  I realize the OP did not make it crystal clear what he was
getting at in his post.  It's easier when you are sitting in the same
office ;-).

> However, I wasn't completely insane, since I came across this tidbit:
>
> http://python.active-venture.com/ref/comparisons.html
>
> "Mappings (dictionaries) compare equal if and only if their sorted (key,
> value) lists compare equal. Outcomes other than equality are resolved
> consistently, but are not otherwise defined."
>
> with a footnote leading to this comment:
>
> "Earlier versions of Python used lexicographic comparison of the sorted
> (key, value) lists, but this was very expensive for the common case of
> comparing for equality."

Ah, I missed that, thanks for the pointer.  Seems information of
dictionary comparisons should also appear in the Library Reference
under Mapping Types.

> I also suggested:
>
>> My second thought was that comparison is implemented by first comparing
>> keys, then values, ie cmp(dictA, dictB)
> [snip]
>> I don't think I can prove it though.

Looking at the source code links Simon posted (thanks Simon!) it is
clear that, in the current version of CPython, dictionaries are
ordered first by length and only if the lengths are equal are the
keys and values examined.

> Equality of dicts is guaranteed. Two dicts are equal if and only if their
> keys:value pairs are equal. Other orderings between dicts are calculated
> consistently but not in any documented way.
>
> One gotcha is that some dicts are unordered:
>
> py> {1:1j} < {1:2j}
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: cannot compare complex numbers using <, <=, >, >=
>
> but even that is special-cased up to the wazzoo:
>
> py> {1:1j} < {1:1j}
> False

Hmm... not sure I like that!

-- 

Aaron Bingham
Senior Software Engineer
Cenix BioScience GmbH


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


Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'

2005-07-12 Thread Cyril Bazin
If that can help you...

def replaceLastComma(s):
    i = s.rindex(",")
    return ' and'.join([s[:i], s[i+1:]])
    
I don't know of ot's better to do a:
' and'.join([s[:i], s[i+1:]])
Or:
''.join([s[:i], ' and', s[i+1:]])
Or:
s[:i] + ' and' + s[i+1]
Maybe the better solution is not in the list...

Cyril
On 7/12/05, Ric Da Force <[EMAIL PROTECTED]> wrote:
Hi,I have a string such as 'C1, C2, C3'.   Without assuming that each bit oftext is of fixed size, what is the easiest way to change this list so thatit reads:'C1, C2 and C3' regardless of the length of the string.
Regards and sorry for the newbie question,Ric--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: set and frozenset unit tests?

2005-07-12 Thread Reinhold Birkenfeld
Jacob Page wrote:
> I have released interval-0.2.1 at 
> http://members.cox.net/apoco/interval/.  IntervalSet and 
> FrozenIntervalSet objects are now (as far as I can tell) functionality 
> equivalent to set and frozenset objects, except they can contain 
> intervals as well as discrete values.
> 
> Though I have my own unit tests for verifying this claim, I'd like to 
> run my code through actual set and frozenset unit tests.  Does any such 
> code exist?  Is it in pure Python?  If so, where can it be obtained?
> 
> Oh, and again, I'd really appreciate additional feedback on the module, 
> especially related to design, if you've got any.  My goal for this 
> project is to make the classes built-in-data-type quality.

Look at /usr/lib/python2.x/test/ (on unix platforms).

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


Re: automatically assigning names to indexes

2005-07-12 Thread simonwittber
> >>> class Vector(tuple):
> ... x = property(lambda self: self[0])
> ... y = property(lambda self: self[1])
> ... z = property(lambda self: self[2])
> ...
> >>> Vector("abc")
> ('a', 'b', 'c')
> >>> Vector("abc").z
> 'c'
> >>> Vector("abc")[2]
> 'c'
>

Aha! You have simultaneously proposed a neat solution, and shown me a
bug in my class! (It shouldn't accept strings)

Thanks.

Sw.

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


Search & Replace with RegEx

2005-07-12 Thread [EMAIL PROTECTED]
Hi Pythonistas,

Here's my problem: I'm using a version of MOOX Firefox
(http://moox.ws/tech/mozilla/) that's been modified to run completely
from a USB Stick. It works fine, except when I install or uninstall an
extension, in which case I then have to physically edit the compreg.dat
file in my profile directory, replacing all instances of Absolute Path
links to relative ones. (And, yes, I have filed a Bugzilla report.)

For example, after installing a new extension, I change in compreg.dat

lines such as:

abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{0538E3E3-7E9B-4d49-8831-A227C80A7AD3}\components\nsForecastfox.js,18590
abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{c4dc572a-3295-40eb-b30f-b54aa4cdc4b7}\components\wml-service.js,111470502

to:

rel:nsForecastfox.js,18590
rel:wml-service.js,111470502

I started a Python script that searches compreg.dat and finds all the
lines that I need to edit. I just need some help using RegEx to search
and replace these lines (as in the examples above), so that I no longer
need to edit compreg.dat manually.

Here's the script that I started:



import os
import re
import fileinput

theRegEx = '.*abs:.*\.*.js.*'

p = re.compile(theRegEx, re.IGNORECASE)

fileToSearch  = 'compreg.dat'
print "File to perfrom search-and-replace on: " + fileToSearch
print "Using Regex: " + theRegEx
print ""

if os.path.isfile( fileToSearch ):
tempFile = open( fileToSearch, 'r' )

for line in fileinput.input( fileToSearch ):
if (p.match(line)!=None):
print line

tempFile.close()

raw_input( '\n\nPress Enter to exit...' )



I'd be very glad to get a helping hand here ;)

Thanks,

Tom

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


Managment of Python Libraries

2005-07-12 Thread Joseph Chase
I am new to Python.

In the past, I have noticed that I have spent a lot of time managing my C++ 
libraries.  When my personal frameworks got large enough, and some moving 
around/refactoring was apparent, it was an absolute nightmare.

As I embark on the wonderful language of Python, or there any object 
organizational tools that may help me to keep order?

Thanks everyone. 


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


Re: Managment of Python Libraries

2005-07-12 Thread Robert Kern
Joseph Chase wrote:
> I am new to Python.
> 
> In the past, I have noticed that I have spent a lot of time managing my C++ 
> libraries.  When my personal frameworks got large enough, and some moving 
> around/refactoring was apparent, it was an absolute nightmare.
> 
> As I embark on the wonderful language of Python, or there any object 
> organizational tools that may help me to keep order?

There's Bicycle Repair Man:

http://bicyclerepair.sourceforge.net/

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Trying to come to grips with static methods

2005-07-12 Thread Steven D'Aprano
I've been doing a lot of reading about static methods in Python, and I'm
not exactly sure what they are useful for or why they were introduced.

Here is a typical description of them, this one from Guido:

"The new descriptor API makes it possible to add static methods and class
methods. Static methods are easy to describe: they behave pretty much like
static methods in C++ or Java."
http://www.python.org/2.2.3/descrintro.html

Great. So I have learn an entire new language to understand static
methods. Perhaps not -- hence this cry for help.

As near as I can see it, static methods are object methods that act just
like functions. Er. I always thought that object methods *were* functions,
except they had some runtime magic that passed the object itself as the
first argument.

>From Guido's example:

>>> class C:
... def foo(x, y):
... print "staticmethod", x, y
... foo = staticmethod(foo)
...
>>> C.foo(1, 2)
staticmethod 1 2
>>> c = C()
>>> c.foo(1, 2)
staticmethod 1 2

So I compare with an ordinary class function, er, method:

>>> class D:
... def foo(self, x, y):
... print "method", x, y
...
>>> D.foo(1, 2)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unbound method foo() must be called with D instance as first 
argument (got int instance instead)

Okay, that is to be expected. Actually, I expected an exception that I
hadn't passed enough arguments (2 arguments when foo expects 3), but in
hindsight it is obvious enough.

First point of confusion. In the above exception, foo is called an unbound
method. But type(D.foo) returns  even though foo is
being access through the class, not an instance. And type(D().foo) returns
the same.

Can I assume that in Python "unbound method" is just another way of saying
"a method of a class that expects to be called via an instance"?



I next tried this:

>>> D.foo(D(), 1, 2)
method 1 2
>>> D().foo(1, 2)
method 1 2

Clear as mud. An ordinary method called from an instance is the same as a
static method called from anywhere, provided you don't -- or rather, can't
-- try to access self from the static method.

When would you use a static method instead of an ordinary method? It has
been suggested that you might use it for functions that don't need to
access self. But that doesn't seem very convincing to me, because there is
already a perfectly good idiom for that:

>>> class E:
... def foo():  # returns calculated value
... return 1
... foo = staticmethod(foo)
... def bar(self):
... return 1  # just ignore the value of self
...
>>> E.foo()
1
>>> e = E()
>>> e.bar()
1

What are some usage cases for using Class.StaticMethod() instead of
instance.method()? Everything I've read seems to just assume that the
benefits of static methods are so obvious that they don't need explaining.
Unfortunately, I haven't come from a background in OO and I'm easily
confused, hence this post.


-- 
Steven.


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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-12 Thread Edvard Majakari
Thorsten Kampe <[EMAIL PROTECTED]> writes:

> Speed considerations and benchmarking should come in after you wrote
> the program. "Premature optimisation is the root of all evil" and
> "first make it work, then make it right, then make it fast" (but only
> if it's not already fast enough) - common quotes not only with Python
> developers.

Just a minor note: regarding quote

"first make it work, then make it right, then make it fast"

Shouldn't one avoid doing it the wrong way from the very beginning? If you
make it "just work" the first time, you'll probably use the old code later on
because "functionality is already there" and temptatation to build on probably
relatively bad architecture can be too strong.

How about

First make it work (but avoid ad-hoc designs), then make it right, then make
it fast

Of course, such emphasis doesn't go well with classic idioms..

(yeah, programmer's block at the moment: I should clean up a 120+ -line
if-elif-elif-elif... else -block which tests a single variable and calls
different methods with variable number of parameters depending on the value of
the variable - guess I should apply command pattern or similar...)

-- 
# Edvard Majakari   Software Engineer
# PGP PUBLIC KEY available  Soli Deo Gloria!

$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to come to grips with static methods

2005-07-12 Thread Cyril Bazin
Im my opinion, class method are used to store some "functions" related to a class in the scope of the class.

For example, I often use static methods like that:
class Foo:
 
On 7/12/05, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
I've been doing a lot of reading about static methods in Python, and I'mnot exactly sure what they are useful for or why they were introduced.Here is a typical description of them, this one from Guido:
"The new descriptor API makes it possible to add static methods and classmethods. Static methods are easy to describe: they behave pretty much likestatic methods in C++ or Java."
http://www.python.org/2.2.3/descrintro.htmlGreat. So I have learn an entire new language to understand staticmethods. Perhaps not -- hence this cry for help.As near as I can see it, static methods are object methods that act just
like functions. Er. I always thought that object methods *were* functions,except they had some runtime magic that passed the object itself as thefirst argument.>From Guido's example:>>> class C:
... def foo(x, y):... print "staticmethod", x, y... foo = staticmethod(foo)...>>> C.foo(1, 2)staticmethod 1 2>>> c = C()>>> c.foo(1, 2)
staticmethod 1 2So I compare with an ordinary class function, er, method:>>> class D:... def foo(self, x, y):... print "method", x, y...>>> D.foo
(1, 2)Traceback (most recent call last):  File "", line 1, in ?TypeError: unbound method foo() must be called with D instance as firstargument (got int instance instead)Okay, that is to be expected. Actually, I expected an exception that I
hadn't passed enough arguments (2 arguments when foo expects 3), but inhindsight it is obvious enough.First point of confusion. In the above exception, foo is called an unboundmethod. But type(D.foo) returns  even though foo is
being access through the class, not an instance. And type(D().foo) returnsthe same.Can I assume that in Python "unbound method" is just another way of saying"a method of a class that expects to be called via an instance"?
I next tried this:>>> D.foo(D(), 1, 2)method 1 2>>> D().foo(1, 2)method 1 2Clear as mud. An ordinary method called from an instance is the same as astatic method called from anywhere, provided you don't -- or rather, can't
-- try to access self from the static method.When would you use a static method instead of an ordinary method? It hasbeen suggested that you might use it for functions that don't need toaccess self. But that doesn't seem very convincing to me, because there is
already a perfectly good idiom for that:>>> class E:... def foo():  # returns calculated value... return 1... foo = staticmethod(foo)... def bar(self):... return 1  # just ignore the value of self
...>>> E.foo()1>>> e = E()>>> e.bar()1What are some usage cases for using Class.StaticMethod() instead ofinstance.method()? Everything I've read seems to just assume that the
benefits of static methods are so obvious that they don't need explaining.Unfortunately, I haven't come from a background in OO and I'm easilyconfused, hence this post.--Steven.--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Trying to come to grips with static methods

2005-07-12 Thread Robert Kern
Steven D'Aprano wrote:
> I've been doing a lot of reading about static methods in Python, and I'm
> not exactly sure what they are useful for or why they were introduced.
> 
> Here is a typical description of them, this one from Guido:
> 
> "The new descriptor API makes it possible to add static methods and class
> methods. Static methods are easy to describe: they behave pretty much like
> static methods in C++ or Java."
> http://www.python.org/2.2.3/descrintro.html
> 
> Great. So I have learn an entire new language to understand static
> methods. Perhaps not -- hence this cry for help.
> 
> As near as I can see it, static methods are object methods that act just
> like functions. Er. I always thought that object methods *were* functions,
> except they had some runtime magic that passed the object itself as the
> first argument.

[snip]

> What are some usage cases for using Class.StaticMethod() instead of
> instance.method()? Everything I've read seems to just assume that the
> benefits of static methods are so obvious that they don't need explaining.
> Unfortunately, I haven't come from a background in OO and I'm easily
> confused, hence this post.

staticmethods don't see a whole lot of use in Python. They see use in 
Java because everything has to be stuck in a class, even if they don't 
actually require an instance of the class to work. In Python, you 
usually just define a function. I think staticmethod was implemented 
along with classmethod primarily for completeness than anything else.

OTOH, I do find myself using them occasionally to group such functions 
appropriately. I'll be writing a utility method that doesn't actually 
need an instance or the class to be passed in, so I make it a 
staticmethod. It *could* just as well be a module-level function, but 
sometimes it really belongs tucked in with the class. It could also be a 
regular method, but then I can't call it from the outside without 
actually having an instance which isn't actually needed. It could also 
be a classmethod, but since it doesn't actually need any information 
from the class to do its work, I find that the extra reminder of 
staticmethod helps my brain understand what it's doing.

All told, I'd probably vote -0.5 on a builtin staticmethod if it came up 
today.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Trying to come to grips with static methods

2005-07-12 Thread Cyril Bazin
(sorry, my fingers send the mail by there own ;-)

Im my opinion, class method are used to store some functionalities (function) related to a class in the scope of the class.
For example, I often use static methods like that:

class Point:
    def __init__(self, x, y):
    self.x, self.y = x, y

    def fromXML(xmlText):
    x, y = functionToParseXMLUsingMinidomForExample(xmlText)
    return Point(x, y)
    fromXML = staticmethod(fromXML)

Here, it is used to define some kind of second constructor... 

Note that class decorator can simplify the notation, but break the compatility with older Python...

Cyril

On 7/12/05, Steven D'Aprano <[EMAIL PROTECTED]
> wrote:
I've been doing a lot of reading about static methods in Python, and I'mnot exactly sure what they are useful for or why they were introduced.Here is a typical description of them, this one from Guido:

"The new descriptor API makes it possible to add static methods and classmethods. Static methods are easy to describe: they behave pretty much likestatic methods in C++ or Java."

http://www.python.org/2.2.3/descrintro.htmlGreat. So I have learn an entire new language to understand staticmethods. Perhaps not -- hence this cry for help.As near as I can see it, static methods are object methods that act just
like functions. Er. I always thought that object methods *were* functions,except they had some runtime magic that passed the object itself as thefirst argument.>From Guido's example:>>> class C:
... def foo(x, y):... print "staticmethod", x, y... foo = staticmethod(foo)...>>> C.foo(1, 2)staticmethod 1 2>>> c = C()>>> c.foo(1, 2)
staticmethod 1 2So I compare with an ordinary class function, er, method:>>> class D:... def foo(self, x, y):... print "method", x, y...>>> 
D.foo
(1, 2)Traceback (most recent call last):  File "", line 1, in ?TypeError: unbound method foo() must be called with D instance as firstargument (got int instance instead)Okay, that is to be expected. Actually, I expected an exception that I
hadn't passed enough arguments (2 arguments when foo expects 3), but inhindsight it is obvious enough.First point of confusion. In the above exception, foo is called an unboundmethod. But type(D.foo) returns  even though foo is
being access through the class, not an instance. And type(D().foo) returnsthe same.Can I assume that in Python "unbound method" is just another way of saying"a method of a class that expects to be called via an instance"?
I next tried this:>>> D.foo(D(), 1, 2)method 1 2>>> D().foo(1, 2)method 1 2Clear as mud. An ordinary method called from an instance is the same as astatic method called from anywhere, provided you don't -- or rather, can't
-- try to access self from the static method.When would you use a static method instead of an ordinary method? It hasbeen suggested that you might use it for functions that don't need toaccess self. But that doesn't seem very convincing to me, because there is
already a perfectly good idiom for that:>>> class E:... def foo():  # returns calculated value... return 1... foo = staticmethod(foo)... def bar(self):... return 1  # just ignore the value of self
...>>> E.foo()1>>> e = E()>>> e.bar()1What are some usage cases for using Class.StaticMethod() instead ofinstance.method()? Everything I've read seems to just assume that the
benefits of static methods are so obvious that they don't need explaining.Unfortunately, I haven't come from a background in OO and I'm easilyconfused, hence this post.--Steven.--

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



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

pychecker filtering

2005-07-12 Thread [EMAIL PROTECTED]
Hi,

I'm trying to make a decent .pycheckrc for our project and have
stumbled on a few issues. (the pychecker-list would have seemed like
the appropriate place, but the S/N ratio seemed very low with all the
spam)

- for various reasons we decided to add an attribute to a module in the
stdlib, lets say os.foo. Now, pychecker screams "No module attribute
(foo) found" in a lot of places, which is not desirable.

(Yes I know, don't do that, fix the original problem etc.. We probably
will eventually, but for now, I just don't want to see those)

I thought of doing something with the suppressions dict, but could not
figure out how to use that in this particular case.

Another thing, we have a lot of autogenerated files which contain a
function _translateException which is basically a huge dictionary
lookup.
Here pychecker complains about too many lines, can I somehow suppress
Wrapper.._translateException or failing that,
all _translateException

(manually including every name does not seem like fun..)


/Simon

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


Re: Trying to come to grips with static methods

2005-07-12 Thread Robert Kern
Cyril Bazin wrote:
> (sorry, my fingers send the mail by there own ;-)
> 
> Im my opinion, class method are used to store some functionalities 
> (function) related to a class in the scope of the class.
> 
> For example, I often use static methods like that:
> 
> class Point:
> def __init__(self, x, y):
> self.x, self.y = x, y
> 
> def fromXML(xmlText):
> x, y = functionToParseXMLUsingMinidomForExample(xmlText)
> return Point(x, y)
> fromXML = staticmethod(fromXML)
> 
> Here, it is used to define some kind of second constructor...
> 
> Note that class decorator can simplify the notation, but break the 
> compatility with older Python...

Huh? classmethod was introduced with staticmethod, and in fact, this use 
case is exactly what classmethods are for, not staticmethods.

In [2]: class Point(object):  # <-- note inheritance from object
...: def __init__(self, x, y):
...: self.x, self.y = x, y
...: def fromXML(cls, xmlText):
...: x, y = parseXML(xmlText)
...: return cls(x, y)
...: fromXML = classmethod(fromXML)
...:

In [3]: class NewPoint(Point):
...: pass
...:

In [4]: def parseXML(xmlText):
...: return 1, 4
...:

In [5]: p = NewPoint.fromXML('')

In [6]: isinstance(p, NewPoint)
Out[6]: True

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-12 Thread Steven D'Aprano
On Tue, 12 Jul 2005 11:38:51 +0300, Edvard Majakari wrote:

> Just a minor note: regarding quote
> 
> "first make it work, then make it right, then make it fast"
> 
> Shouldn't one avoid doing it the wrong way from the very beginning? If you
> make it "just work" the first time, you'll probably use the old code later on
> because "functionality is already there" and temptatation to build on probably
> relatively bad architecture can be too strong.
> 
> How about
> 
> First make it work (but avoid ad-hoc designs), then make it right, then make
> it fast

Optimizing sometimes means refactoring your code. Sometimes it even means
throwing it away and starting again.

However, your point to bring us back to a discussion held on this
newsgroup not long ago, about whether or not it was good for computer
science students to learn how to program in low-level languages like C so
as to avoid silly mistakes like this:

result = ""
for s in really_big_list_of_strings:
result = result + s
return result

instead of just "".join(really_big_list_of_strings).

The first method is slow, but you might not know that unless you have some
understanding of the implementation details of string concatenation.

My opinion is, no, you don't need to be a C programmer, or an assembly
programmer, or a hardware level physicist who understands NAND gates, but
it is very useful to have some understanding of what is going on at the
low-level implementation.

The way I see it, programmers need to be somewhat aware of the eventual
optimization stage in their program, so as to avoid poor design choices
from the start. But you can't always recognise poor design up front, so
even more important is careful encapsulation and design, so you
can make significant implementation changes without needing to throw away
your work. (Well, that's the theory.)


-- 
Steven.

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


Re: Trying to come to grips with static methods

2005-07-12 Thread Cyril Bazin
Ok, sorry, you are right Robert. 

What about this one: 

class Parser(object):
    def toParser(p):
    if type(p) == str:
    if len(p) == 1:
    return lit(p)
    return txt(p)
    return p
    toParser = staticmethod(toParser)

This is meant to translate p to a parser if it's not one.
'lit' is a function that take a string of length 1 and return a parser of char.
'txt' is a function that take a string of any length and return a parser.
I hope it is a better example!
That one of the rare case I used static method in Python...

Cyril
On 7/12/05, Robert Kern <[EMAIL PROTECTED]> wrote:
Cyril Bazin wrote:> (sorry, my fingers send the mail by there own ;-)>> Im my opinion, class method are used to store some functionalities> (function) related to a class in the scope of the class.
>> For example, I often use static methods like that:>> class Point:> def __init__(self, x, y):> self.x, self.y = x, y>> def fromXML(xmlText):> x, y = functionToParseXMLUsingMinidomForExample(xmlText)
> return Point(x, y)> fromXML = staticmethod(fromXML)>> Here, it is used to define some kind of second constructor...>> Note that class decorator can simplify the notation, but break the
> compatility with older Python...Huh? classmethod was introduced with staticmethod, and in fact, this usecase is exactly what classmethods are for, not staticmethods.In [2]: class Point(object):  # <-- note inheritance from object
...: def __init__(self, x, y):...: self.x, self.y = x, y...: def fromXML(cls, xmlText):...: x, y = parseXML(xmlText)...: return cls(x, y)...: fromXML = classmethod(fromXML)
...:In [3]: class NewPoint(Point):...: pass...:In [4]: def parseXML(xmlText):...: return 1, 4...:In [5]: p = NewPoint.fromXML('')
In [6]: isinstance(p, NewPoint)Out[6]: True--Robert Kern[EMAIL PROTECTED]"In the fields of hell where the grass grows high  Are the graves of dreams allowed to die."
   -- Richard Harter--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Sort files by date

2005-07-12 Thread fargo
Hi.

I'm looking for some way to sort files by date.

I'm usin glob module to list a directiry, but files are sorted by name.

 >>> import glob
 >>> path = "./"
 >>> for ScannedFile in glob.glob(path):
... print ScannedFile

I googled my problem, but did not find any solution, neither in this 
newsgroup.

Can anyone help me ?

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


Re: Efficiency of using long integers to hold bitmaps

2005-07-12 Thread Jeff Melvaine
Raymond,

Thanks for your answers, which even covered the question that I didn't ask 
but should have.

 "A Python list is not an array()\n" * 100  :)

Jeff

"Raymond Hettinger" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> [Jeff Melvaine]
>> I note that I can write expressions like "1 << 100" and the result is 
>> stored
>> as a long integer, which means it is stored as an integer of arbitrary
>> length.  I may need to use a large number of these, and am interested to
>> know whether the storage efficiency of long integers is in danger of
>> breaking my code if I use too many.  Would I do better to write a class 
>> that
>> defines bitwise operations on arrays of integers, each integer being 
>> assumed
>> to contain at most 32 bits?
>
>
> Both array() objects and long integers are equally space efficient.
> In contrast, a list of integers takes up a lot of space (the list is
> stored as an array of pointers to individual integer objects).
>
> Raymond
> 


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


Re: Sort files by date

2005-07-12 Thread Jeremy Sanders
fargo wrote:

> I'm looking for some way to sort files by date.

you could do something like:

l = [(os.stat(i).st_mtime, i) for i in glob.glob('*')]
l.sort()
files = [i[1] for i in l]

Jeremy

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort files by date

2005-07-12 Thread fargo
Jeremy Sanders wrote:

> you could do something like:
> 
> l = [(os.stat(i).st_mtime, i) for i in glob.glob('*')]
> l.sort()
> files = [i[1] for i in l]

Thank you for your help, this is excatly what I wasa looking for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Creating anonymous functions using eval

2005-07-12 Thread Julian Smith
I've been playing with a function that creates an anonymous function by
compiling a string parameter, and it seems to work pretty well:

def fn( text):
exec 'def foo' + text.strip()
return foo

This can be used like:

def foo( x):
print x( 2, 5)

foo( fn( '''
( x, y):
print 'x^2 + y^2 = ', x*x + y*y
return y
'''))

- which outputs:

x^2 + y^2 =  29
5


You can also mimic conventional function definitions:

f = fn( '''
( x, y):
print 'x, y=', x, y
print 1.0*x/y
return y
''')

print 'calling f'
f( 5, 6)

This outputs:

calling f
x, y= 5 6
0.8333


You do things like allow/require an initial `def' for clarity, check that all
the lines of text are indented so that nothing is executed when the anonymous
function is created, etc etc.

Obvious disadvantages are that the function text may have to escape quotes,
and will not be showed with syntax colouring in editors.

Apart from that, it seems quite a useful way of overcoming the limitations of
python's lambda.

But... I haven't seen this technique mentioned anywhere, so does anyone know
of any problems that I should be wary of?

- Julian

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


Inconsistency in hex()

2005-07-12 Thread Steven D'Aprano
hex() of an int appears to return lowercase hex digits, and hex() of a
long uppercase.

>>> hex(75)
'0x4b'
>>> hex(75*256**4)
'0x4BL'

By accident or design? Apart from the aesthetic value that lowercase hex
digits are ugly, should we care?

It would also be nice if that trailing L would disappear.

-- 
Steven.

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


Re: Web App like Google

2005-07-12 Thread Robert Kern
godwin wrote:
> Hello there,
>   I need some thoughts about a web application that i am dreaming
> and drooling about in python. I want a search page to look exactly like
> Google. But when i press the search button, it should search a database
> in an rdbms like Oracle and provide results.
>  For example, if my keywords are "all customers with names
> starting with 'God'" it should somehow search table CUSTOMER , with
> following query :
>   SELECT CUSTNAME FROM CUSTOMER WHERE CUSTNAME LIKE 'God%'

This is a Natural Language Processing (NLP) task. In general, it's 
pretty hard. For Python, there is the Natural Language Toolkit (NLTK):

   http://nltk.sourceforge.net/

You could get pretty far, though, by accepting a specific subset, the 
so-called "controlled natural language" approach. For example:

   http://www.jfsowa.com/clce/specs.htm
   http://www.ics.mq.edu.au/~rolfs/controlled-natural-languages/
   http://www.ifi.unizh.ch/attempto/

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: What is Expresiveness in a Computer Language?

2005-07-12 Thread Xah Lee
Most participants in the computering industry should benefit in reading
this essay:

George Orwell's “Politics and the English Language”, 1946.
Annotated:

 http://xahlee.org/p/george_orwell_english.html

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: how to stop execution in interactive window?

2005-07-12 Thread siggy2
> Right-click on the Pythonwin icon in the tray and select "Break into running
> code".
[CUT]

Thanks a lot! Oddly enough I'm looking into PythonWin manual to see why

I did not find it before... and there is no mention of it!

Now if only I could find out how to free pythonwin interactive window
memory
(I'm not talking about interactive window output - cleanable with
ctrl-a + delete,
but about variable valorization, function definition etc )...
IIRC there was already a post in this newsgroup that explained how to
do this...
but yesterday google searches return me that the only way was to force
this by
closing and re-opening pythonwin...
Maybe I was wrong and there's no other way...
Again: thanks a lot for your help!
bye,
   PiErre

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


Re: automatically assigning names to indexes

2005-07-12 Thread George Sakkis
<[EMAIL PROTECTED]> wrote:

> I know its been done before, but I'm hacking away on a simple Vector
> class.
>
> class Vector(tuple):
> def __add__(self, b):
> return Vector([x+y for x,y in zip(self, b)])
> def __sub__(self, b):
> return Vector([x-y for x,y in zip(self, b)])
> def __div__(self, b):
> return Vector([x/b for x in self])
> def __mul__(self, b):
> return Vector([x*b for x in self])
>
> I like it, because it is simple, and can work with vectors of any
> size...
>
> However, I'd like to add attribute access (magically), so I can do
> this:
>
> v = Vector((1,2,3))
> print v.x
> print v.y
> print v.z
>
> as well as:
>
> print v[0]
> print v[1]
> print v[2]
>
> Has anyone got any ideas on how this might be done?

And what should happen for vectors of size != 3 ? I don't think that a
general purpose vector class should allow it; a Vector3D subclass would
be more natural for this.

George

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


Re: a new Python Podcast series (and the use of Python in creating podcasting tools)

2005-07-12 Thread rdsteph
I'd love to get some guest "lectures" from advanced folks, and
interviews with prominent Pythonista people etc.

Ron

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


Re: Managment of Python Libraries

2005-07-12 Thread Benji York
Joseph Chase wrote:
> In the past, I have noticed that I have spent a lot of time managing my C++ 
> libraries. 

The main thing you need are good tests.
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Software needed

2005-07-12 Thread niXin
Hi

Can anyone direct me to where I can find free software to do the following:

Document Management Software
---

1. Written in PHP or Python
2. scanning feature - where I can scan a document


I'm basically trying to setup a paperless office..lol

If you could help that would be great.

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


Re: cursor positioning

2005-07-12 Thread Mage
Danny Milosavljevic wrote:

>Hi,
>
>  
>
>Examples
>  ESC[2JESC[H  same as "clear", clear screen, go home
>  \rESC[Kprogress %dprobably what you want :)
>  
>
Well, like the good old Commodore times :)
Thank you.

   Mage


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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-12 Thread Peter Hansen
Edvard Majakari wrote:
> "first make it work, then make it right, then make it fast"
> 
> Shouldn't one avoid doing it the wrong way from the very beginning? If you
> make it "just work" the first time, you'll probably use the old code later on
> because "functionality is already there" and temptatation to build on probably
> relatively bad architecture can be too strong.

The expression describes (most recently, if not originally) the practice 
in Test-Driven Development (TDD) of making your code pass the test as 
quickly as possible, without worrying about how nice it is.

The "right" part doesn't refer to correctness, but to structure, style, 
readability, and all those other nice things that an automated test 
can't check.  You aren't doing it "wrong" at first, just expediently.

And it really does make sense, because at that early stage, you aren't 
even absolutely certain that your test is entirely correct, so making 
your code a paragon of elegance is a potential waste of time, and 
distracting.  Once you've been able to pass that test (and all the 
others, since you have to make sure all previous tests still pass as 
well), then and only then is it sensible -- and required! -- to refactor 
the code to make it elegant, concise, clean, etc.

Of course, your point about temptation is sound.  Extreme Programming 
tries to avoid that problem partly by pairing programmers together, and 
it is the responsibility of both partners to encourage^H^H^H^H^H insist 
that the refactor "make it right" stage must occur _now_, before we 
check the code in.  If you skip this step, you're failing to be an agile 
programmer, and your code base will become a tar pit even more quickly 
than it would in a traditional (non-agile) project...

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


Re: math.nroot [was Re: A brief question.]

2005-07-12 Thread Michael Hudson
I doubt anyone else is reading this by now, so I've trimmed quotes
fairly ruthlessly :)

Tim Peters <[EMAIL PROTECTED]> writes:

> > Actually, I think I'm confused about when Underflow is signalled -- is it
> > when a denormalized result is about to be returned or when a genuine
> > zero is about to be returned?
> 
> Underflow in 754 is involved -- indeed, the definition is different
> depending on whether the underflow trap is or is not enabled(!). 

!

> > Sure, but we already have a conforming implementation of 854 with
> > settable traps and flags and rounding modes and all that jazz.
> 
> No, we don't, but I assume you're talking about the decimal module. 

Uh, yes.  Apologies for the lack of precision.

> If so, the decimal module enables traps on overflow, invalid
> operation, and divide-by-0 by default.  A conforming implementation
> would have to disable them by default.
> 
> Apart from that difference in defaults, the decimal module does intend
> to conform fully to the proposed decimal FP standard.

Right, that's what I meant.

> > Maybe we should just implement floats in Python.
> 
> Certainly the easiest way to get 754 semantics across boxes!  Been
> there, done that, BTW -- it's mondo slow.

No doubt.

> >>> (In the mean time can we just kill fpectl, please?)
> 
> >> Has it been marked as deprecated yet (entered into the PEP for
> >> deprecated modules, raises deprecation warnings, etc)?  I don't know.
> >> IMO it should become deprecated, but I don't have time to push that.
> 
> > A bit of googling suggests that more people pass --with-fpectl to
> > configure than I expected, but I doubt more than 1% of those actually
> > use the features thus provided (of course, this is a guess).
> 
> I expect 1% is way high.  Before we stopped building fpectl by
> default, Guido asked and heard back that there were no known users
> even at LLNL anymore (the organization that contributed the code).

Interesting.

>  You're seeing native HW fp behavior then.
> 
> >>> But anyway, shouldn't we try to raise exceptions in these cases?
> 
> Note that the only cases you could have been talking about here were
> the plain * and / examples above.

Ah, OK, this distinction passed me by.

> >> Why doesn't Python already supply a fully 754-conforming arithmetic
> >> on 754 boxes?  It's got almost everything to do with implementation
> >> headaches, and very little to do with what users care about.
> >> Because all the C facilities are a x-platform mess, the difference
> >> between calling and not calling libm can be the difference between
> >> using the platform libm or Python needing to write its own libm.
> >> For example, there's no guarantee that math.sqrt(-1) will raise
> >> ValueError in Python, because Python currently relies on the
> >> platform libm sqrt to detect _and report_ errors.  The C standards
> >> don't require much of anything there.
> 
> > Can't we use the stuff defined in Appendix F and header  of
> > C99 to help here?  I know this stuff is somewhat optional, but it's
> > available AFAICT on the platforms I actually use (doesn't mean it
> > works, of course).
> 
> It's entirely optional part of C99.  

Hmm, is  optional?  I'm not finding those words.  I know
Appendix F is.

> Python doesn't require C99.

Sure.  But it would be possible to, say, detect C99 floating point
facilities at ./configure time and use them if available.

> The most important example of a compiler that doesn't support any of
> that stuff is Microsoft's, although they have their own MS-specific
> ways to spell most of it.

OK, *that's* a serious issue.

If you had to guess, do you think it likely that MS would ship fenv.h
in the next interation of VC++?

> > I'm thinking something like this:
> >
> > fexcept_t flags;
> >
> > feclearexcept(FE_ALL_EXCEPT);
> >
> > /* stuff, e.g. r = exp(PyFloat_AS_DOUBLE(x)) */
> >
> > fegetexceptflag(&flags, FE_ALL_EXCEPT)
> > 
> > /* inspect flags to see if any of the flags we're currently trapping
> >   are set */
> 
> Assuming the platform libm sets 754 flags appropriately, that's a fine
> way to proceed on platforms that also support that specific spelling.

It even seems to work, on darwin/ppc (so, with GCC) at least.

> ...
> 
> >>> Well, you can at least be pretty sure that an infinite result is the
> >>> result of an overflow condition, I guess.
> 
> > > There are at least two other causes:  some cases of divide-by-0 (like
> > > 1/0 returns +Inf), and non-exceptional production of an infinite
> > > result from infinite operands (like sqrt(+Inf) should return +Inf, and
> > > there's nothing exceptional about that).
> 
> > Yeah, but I think those can be dealt with (if we really wanted to).
> 
> They certainly could be.

The more I think about it, the less wise I think detecting stuff this
was is sane.

> >> BTW, since there's so little the HW can help us with here in reality
> >> (since there's no portable way to get at it),
> 
> > In what way does C99's fenv.h fail?  Is it just insuf

Re: relative import packages/modules workaround

2005-07-12 Thread peter
hmm,

it seems to be less trivial than you mentioned...

hopefully this will be introduced fast in python

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


Re: Search & Replace with RegEx

2005-07-12 Thread George Sakkis
<[EMAIL PROTECTED]> wrote:

[snipped]

> For example, after installing a new extension, I change in compreg.dat
>
> lines such as:
>
> abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{0538E3E3-7E9B-4d49-8831-A227C80A7AD3}\components\nsForecastfox.js,18590
> abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{c4dc572a-3295-40eb-b30f-b54aa4cdc4b7}\components\wml-service.js,111470502
>
> to:
>
> rel:nsForecastfox.js,18590
> rel:wml-service.js,111470502

Try this:

import re
from fileinput import FileInput

regex = re.compile(r'^abs:.*\\(.+)$')
input = FileInput(filename)
unparsed = []

for line in input:
try:
print regex.match(line).group(1)
except:
unparsed.append(input.filelineno())
print line

print "Unparsed lines:", ','.join(map(str,unparsed))

George

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


Re: Tricky Dictionary Question from newbie

2005-07-12 Thread James Carroll
Notice the dictionary is only changed if the key was missing.

>>> a = {}
>>> a.setdefault("a", "1")
'1'
>>> a.setdefault("a", "2")
'1'
>>> a.setdefault("b", "3")
'3'
>>> a
{'a': '1', 'b': '3'}
>>> a.setdefault("a", "5")
'1'
>>> a
{'a': '1', 'b': '3'}

-Jim

On 7/11/05, Peter Hansen <[EMAIL PROTECTED]> wrote:
> Ric Da Force wrote:
> > How does setdefault work exactly? I am looking in the docs and can't figure
> > it out...
> 
> If the key (the first argument) already exists in the dictionary, the
> corresponding value is returned.  If the key does not exist in the
> dictionary, it is stored in the dictionary and bound to the second
> argument, and then that second argument is returned as the value.
> 
> (I always have to ignore the name to think about how it works, or it
> gets in the way of my understanding it.  The name makes fairly little
> sense to me.)
> 
> -Peter
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing Data, Storing into an array, Infinite Backslashes

2005-07-12 Thread [EMAIL PROTECTED]
Thanks for all the help, I'm not sure what approach I'm going to try
but I think I'll try all of your suggestions and see which one fits
best.

The variable "i" held the following array:

[['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed',
'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ['Memory', '0',
'Size', '512'], ['Memory', '0', 'Slot', 'DIMM0/J11'], ['Memory', '0',
'ConfigurationType', '2'], ['Memory', '1', 'Summary', '0'], ['Memory',
'1', 'Speed', 'PC3200U-30330'], ['Memory', '1', 'Type', 'DDR SDRAM'],
['Memory', '1', 'Size', '512'], ['Memory', '1', 'Slot', 'DIMM1/J12'],
['Memory', '1', 'ConfigurationType', '2'], ['Memory', '2', 'Summary',
'0'], ['Memory', '2', 'Speed', 'PC3200U-30330'], ['Memory', '2',
'Type', 'DDR SDRAM'], ['Memory', '2', 'Size', '512'], ['Memory', '2',
'Slot', 'DIMM2/J13'],

> Where is the fetch object defined? And what is it supposed to be
> returning?

Fetch is declared a few lines up in the program with this
fetch=iter(ed) it just goes through the array and returns the next part
of it.

>> query[count]=qval+i[2]+"="+i[3]+", "

>Impossible to know what this does since we don't know what i is. Hint: it
>is easier to read and parse expressions by adding a small amount of
>whitespace:

I am trying to assign each new memory slot to a new part in the array.
So when memory is either 0,1,2,3 it will assign it to query[0],
query[1], query[2], query[3]

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


Re: Tricky Dictionary Question from newbie

2005-07-12 Thread Peter Hansen
(Fixed top-posting)

James Carroll wrote:
 > On 7/11/05, Peter Hansen <[EMAIL PROTECTED]> wrote:
 >>(I always have to ignore the name to think about how it works, or it
 >>gets in the way of my understanding it.  The name makes fairly little
 >>sense to me.)

> Notice the dictionary is only changed if the key was missing.

James, I'll assume your reply was intended to address my comment above.

It's not so much that the concept of "set the default value for this 
key" is poorly captured by the name "setdefault", but that the function 
is used almost exclusively in the idiom below, where it is critical that 
it also _returns_ the value, which is usually then operated on 
immediately, usually in the same line of code.

dict.setdefault(key, defaultValue).someMethodOnKey()

or

dict.setdefault(key, defaultValue) #= value, where # is some operator.

I suppose I shouldn't blame setdefault() itself for being poorly named, 
but it's confusing to me each time I see it in the above, because the 
name doesn't emphasize that the value is being returned, and yet that 
fact is arguably more important than the fact that a default is set!

I can't think of a better name, though, although I might find "foo" less 
confusing in the above context. :-)

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


Re: automatically assigning names to indexes

2005-07-12 Thread François Pinard
[EMAIL PROTECTED]

> I know its been done before, but I'm hacking away on a simple Vector
> class. [...] However, I'd like to add attribute access (magically),
> so I can do this: [...] Has anyone got any ideas on how this might be
> done?

I needed something this last week, while toying with rotations.  Allow
me to humbly offer my solution, meant for more than one class.  Yet for
brievety, I'm limiting my example to a single class.  A few constructors
are used in the example, but the corresponding classes are missing.

I hesitated a bit between having my rotation objects be modifiable or
not, and finally opted for the later (consequently, the constructor is
neatly called for a resulting object).  If you really want a modifiable
object, derive from `list' instead of deriving from `tuple', rename
`NamedTuple' into `NamedList', and wihin sub-classes, initialise your
object with `__init__(self, ...)' rather than with `__new__(cls, ...)'.



__metaclass__ = type
import math

# Almost zero, but not yet.
epsilon = 1e-9

from math import pi
half_pi = .5*pi

class NamedTuple(tuple):

class __metaclass__(type):

def __new__(cls, name, bases, definitions):
self = type.__new__(cls, name, bases, definitions)
if hasattr(self, '__names__'):
def make_property(index):
def getter(self): return self[index]
return property(getter)
for index, name in enumerate(self.__names__):
setattr(self, name, make_property(index))
return self

class Quaternion(NamedTuple):
__names__ = 'w', 'x', 'y', 'z'

def __new__(cls, w, x, y, z):
l = 1./math.sqrt(w*w + x*x + y*y + z*z)
return cls.new(w*l, x*l, y*l, z*l)

def new(cls, w, x, y, z):
if w < 0.:
self = tuple.__new__(cls, (-w, -x, -y, -z))
else:
self = tuple.__new__(cls, (w, x, y, z))
assert self.is_normal(), self
return self
new = classmethod(new)

def is_normal(self):
# For debugging only.
w, x, y, z = self
return abs(w*w + x*x + y*y + z*z - 1.) < epsilon and w >= 0.

def __eq__(self, other):
w1, x1, y1, z1 = self
w2, x2, y2, z2 = other
return abs(w1-w2) + abs(x1-x2) + abs(y1-y2) + abs(z1-z2) < epsilon

def __ne__(self, other):
return not self == other

def __mul__(self, other):
w1, x1, y1, z1 = self
w2, x2, y2, z2 = other
return Quaternion.new(w1*w2 - x1*x2 - y1*y2 - z1*z2,
  w1*x2 + x1*w2 + y1*z2 - z1*y2,
  w1*y2 + y1*w2 - x1*z2 + z1*x2,
  w1*z2 + z1*w2 + x1*y2 - y1*x2)

def __div__(self, other):
w1, x1, y1, z1 = self
w2, x2, y2, z2 = other
return Quaternion.new( w1*w2 + x1*x2 + y1*y2 + z1*z2,
  -w1*x2 + x1*w2 - y1*z2 + z1*y2,
  -w1*y2 + y1*w2 + x1*z2 - z1*x2,
  -w1*z2 + z1*w2 - x1*y2 + y1*x2)

def __rdiv__(self, other):
if not isinstance(other, (int, long, float)):
raise TypeError("unsupported operand type(s) for /")
w, x, y, z = self
return Quaternion.new(w, -x, -y, -z)

__truediv__ = __div__
__rtruediv__ = __rdiv__

def euler(self):
w, x, y, z = self
x2 = x + x
y2 = y + y
z2 = z + z
xx2 = x2*x
yy2 = y2*y
zz2 = z2*z
wx2 = x2*w
wy2 = y2*w
wz2 = z2*w
xy2 = x2*y
yz2 = y2*z
zx2 = z2*x
siny = wy2 - zx2
if abs(abs(siny) - 1) > epsilon:
return Euler.new(math.asin(siny),
 math.atan2(yz2 + wx2, 1. - xx2 - yy2),
 math.atan2(xy2 + wz2, 1. - yy2 - zz2))
if siny > 0.:
y = half_pi
else:
y = -half_pi
return Euler.new(math.atan2(-(yz2 - wx2), 1. - xx2 - zz2), y, 0.)

def matrix(self):
w, x, y, z = self
x2 = x + x
y2 = y + y
z2 = z + z
xx2 = x2*x
yy2 = y2*y
zz2 = z2*z
wx2 = x2*w
wy2 = y2*w
wz2 = z2*w
xy2 = x2*y
yz2 = y2*z
zx2 = z2*x
return Matrix(1. - yy2 - zz2, xy2 + wz2,  zx2 - wy2,
  xy2 - wz2,  1. - xx2 - zz2, yz2 + wx2,
  zx2 + wy2,  yz2 - wx2,  1. - xx2 - yy2)

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled

2005-07-12 Thread Colin J. Williams
Bengt Richter wrote:
> On Mon, 11 Jul 2005 22:10:33 -0400, "Colin J. Williams" <[EMAIL PROTECTED]> 
> wrote:
> 
> 
>>The snippet of code below gives the result which follows
>>
>>for k in ut.keys():
>>  name= k.split('_')
>>  print '\n1', name
>>  if len(name) > 1:
>>name[0]= name[0] + name[1].capitalize()
>>print '2', name
>>  name[0]= name[0].capitalize()
>>  print '3', name
>>
>>1 ['logical', 'or']
>>2 ['logicalOr', 'or']
>>3 ['Logicalor', 'or']
>>
>>I was expecting that 3 would read ['LogicalOr', 'or']
>>
>>If I replace the above code with:
>>
>>for k in ut.keys():
>>  name= k.split('_')
>>  print '\n1', name
>>  if len(name) > 1:
>>name[0]= name[0].capitalize() + name[1].capitalize()
>>print '2', name
>>  else:
>>name[0]= name[0].capitalize()
>>  print '3', name
>>
>>I get the desired result.
>>
> 
> If you walk through the results, you can see what happens to name[2] on 
> output line 2:
> 
>  >>> 'logicalOr'.capitalize()
>  'Logicalor'
> 
> I.e., 
>  >>> help(str.capitalize)
>  Help on method_descriptor:
> 
>  capitalize(...)
>  S.capitalize() -> string
> 
>  Return a copy of the string S with only its first character
>  capitalized.   -- meaning all the rest 
> lowercased,
>which changed your trailing 
> 'Or'
> 
> So, doing .capitalize on all the pieces from split('_') and then joining them:
> 
>  >>> def doit(w): return ''.join([s.capitalize() for s in w.split('_')])
>  ...
>  >>> doit('logical_or')
>  'LogicalOr'
>  >>> doit('logical')
>  'Logical'
>  >>> doit('logical_or_something')
>  'LogicalOrSomething'
>  >>> doit('UP_aNd_down')
>  'UpAndDown'
> 
> Regards,
> Bengt Richter
Many thanks. I missed the implication that any upper case characters 
after the first are changed to lower case.

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


Missing Something Simple

2005-07-12 Thread John Abel
Hi,

I have a list of variables, which I am iterating over.  I need to set 
the value of each variable.  My code looks like:

varList = [ varOne, varTwo, varThree, varFour ]

for indivVar in varList:
indivVar = returnVarFromFunction()

However, none of the variables in the list are being set.  I thought of 
using setattr, but this code sits in a function, and not class, so I'm 
unsure what the object would be.

I'm hoping someone can point me in the right direction.

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


append one file to another

2005-07-12 Thread [EMAIL PROTECTED]
Hi,

I want to append one (huge) file to another (huge) file.  The current
way I'm doing it is to do something like:

infile = open (infilename, 'r')
filestr = infile.read()
outfile = open(outfilename, 'a')
outfile.write(filestr)

I wonder if there is a more efficient way doing this?
Thanks.

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


CONNCET TO SOAP SERVICE

2005-07-12 Thread Slaheddine Haouel








Can you help me plz ? I want to wonnect to SOAP
webservices but before I must be authentificated on a apache server, I used
SOAPpy module but I don’t know how I can be authentified on the apache
server

 

thx

 

Slaheddine Haouel

Unilog NORD

tél : 03 59 56 60 25

tél support  : 03 59 56 60 68

Email : [EMAIL PROTECTED]

 






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

RE: Yet Another Python Web Programming Question

2005-07-12 Thread Sells, Fred
FWIW there's  "dos2unix" program that fixes this on most systems.

-Original Message-
From: Bill Mill [mailto:[EMAIL PROTECTED]
Sent: Monday, July 11, 2005 11:55 AM
To: Daniel Bickett
Cc: python-list@python.org
Subject: Re: Yet Another Python Web Programming Question


> Python using CGI, for example, was enough for him until he started
> getting 500 errors that he wasn't sure how to fix.

A common error is that python cgi files need line endings to be in
unix text file format, not windows text file format (\n instead of
\r\n) [1]. Why this is, I don't know, but it causes a lot of errors
for windows folks. I'm a frequent linux/windows switcher, and it's
caused me no end of troubles - if you're getting "premature end of
script headers" in your apache error logs, this may be your problem.

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API : Creating a Py_Method object from a C function.

2005-07-12 Thread Hugh Macdonald
Thanks Martin - that worked wonderfully


For the record (and for anyone searching for this in future), here's
the code that worked (with names changed to protect my job...)


myPython is the C++/Python interface class containing static methods
which pass on calls to the underlying python module. It's not really
commented, but if you're trying to do this kind of thing, it should
give you what you need.


// myPython.h

#ifndef ___MYPYTHON_H___
#define ___MYPYTHON_H___

#include 

using namespace std;

typedef struct _object PyObject;
typedef void   (*loadCallback)(string message, int progress, void
*callbackData);

staticPyObject *myPython_doLoadCallback(PyObject *self,
PyObject *args);

class myPython {
public:
staticlist *loadDetails(string file, loadCallback
callbackFunc = NULL, void *callbackData = NULL);
staticvoid doLoadCallback(string message, int
progress);
private:
staticPyObject *getResults(char *moduleName, char
*functionName, PyObject *args);

staticloadCallback callbackFunc;
staticvoid *callbackData;
};

#endif // ___MYPYTHON_H___




// myPython.cpp

#include 
#include 

loadCallbackmyPython::callbackFunc = NULL;
void*myPython::callbackData = NULL;

list *myPython::loadDetails(string file, loadCallback
newCallbackFunc, void *newCallbackData)
{
PyObject *pArgs, *pResult;

callbackFunc = newCallbackFunc;
callbackData = newCallbackData;

PyMethodDef *callbackFunctionDef = new PyMethodDef;
callbackFunctionDef->ml_name = "doLoadCallback";
callbackFunctionDef->ml_meth = &myPython_doLoadCallback;
callbackFunctionDef->ml_flags = 1;

PyObject *pyCallbackFunc = PyCFunction_New(callbackFunctionDef,
NULL);

pArgs = Py_BuildValue("(sO)", file.c_str(), pyCallbackFunc);

pResult = getResults("myPythonModule", "loadDetails", pArgs);

if(!pResult)
{
Py_DECREF(pArgs);
return NULL;
}

if(PyList_Check(pResult))
{
// Convert pResult into a list and return that.
}

return NULL;
}

PyObject *myPython_doLoadCallback(PyObject *self, PyObject *args)
{
char *message;
int progress;

if(!PyArg_ParseTuple(args, "si", &message, &progress))
return NULL;

myPython::doLoadCallback(message, progress);

return Py_None;
}

void myPython::doLoadCallback(string message, int progress)
{
if(callbackFunc)
callbackFunc(message, progress, callbackData);
}


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


Re: append one file to another

2005-07-12 Thread Thomas Guettler
Am Tue, 12 Jul 2005 06:47:50 -0700 schrieb [EMAIL PROTECTED]:

> Hi,
> 
> I want to append one (huge) file to another (huge) file.  The current
> way I'm doing it is to do something like:
> 
> infile = open (infilename, 'r')
> filestr = infile.read()
> outfile = open(outfilename, 'a')
> outfile.write(filestr)
> 
> I wonder if there is a more efficient way doing this?
> Thanks.

I guess (don't know), that this is faster:

for line in infile:
outfile.write(line)

At least if this a file with "lines".

If it is a binary file, you could read 
N bytes at once: infile.read(N)

 Thomas


-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: Search & Replace with RegEx

2005-07-12 Thread Thomas Guettler
Am Tue, 12 Jul 2005 01:11:44 -0700 schrieb [EMAIL PROTECTED]:

> Hi Pythonistas,
> 
> Here's my problem: I'm using a version of MOOX Firefox
> (http://moox.ws/tech/mozilla/) that's been modified to run completely
> from a USB Stick. It works fine, except when I install or uninstall an
> extension, in which case I then have to physically edit the compreg.dat
> file in my profile directory, replacing all instances of Absolute Path
> links to relative ones. (And, yes, I have filed a Bugzilla report.)
> 
> For example, after installing a new extension, I change in compreg.dat
> 
> lines such as:
> 
> abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{0538E3E3-7E9B-4d49-8831-A227C80A7AD3}\components\nsForecastfox.js,18590
> abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{c4dc572a-3295-40eb-b30f-b54aa4cdc4b7}\components\wml-service.js,111470502
> 
> to:
> 
> rel:nsForecastfox.js,18590
> rel:wml-service.js,111470502

Hi,

some time ago I wrote "replace-recursive.py":

http://www.thomas-guettler.de/scripts/replace_recursive.py.txt

Maybe this helps you,

  Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: Missing Something Simple

2005-07-12 Thread harold fellermann
Hi,

> I have a list of variables, which I am iterating over.  I need to set
> the value of each variable.  My code looks like:
>
> varList = [ varOne, varTwo, varThree, varFour ]
>
> for indivVar in varList:
> indivVar = returnVarFromFunction()
>
> However, none of the variables in the list are being set.

You only change the value of the local variable in the body
of the for loop. it has no effect on the list. you could do e.g.

varList = [vorOne,varTwo,varThree,varFour]
for i in len(varList) :
varList[i] = returnVarFromFunction()

However, as in this example the former list values are not used anyway,
you could just write:

varList = [ returnVarFromFunction for i varList ]


cheers,

- harold -

--
Tages Arbeit, abends Gäste,
saure Wochen, frohe Feste!
-- Johann Wolfgang v. Goethe

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


CAD in wxPython

2005-07-12 Thread [EMAIL PROTECTED]
Hi all,
  I am trying to write a small program to view VLSI mask layouts.

I am trying to display polygons with different *transparent* patterns.
How can I do this in wxPython. Can you please give me some pointers if
some application has already done this.

Look at the images in these web pages. I am trying to create something
like this.
http://vsp2.ecs.umass.edu/vspg/658/TA_Tools/cadence/Vertuoso.html
http://www.cisl.columbia.edu/grads/sumit/layout.html

My dream is to develop a full fledged eda environment on top of python.
If you are also interested contact me.

Thanks.

regards,
Suresh

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


Re: automatically assigning names to indexes

2005-07-12 Thread simonwittber

> And what should happen for vectors of size != 3 ? I don't think that a
> general purpose vector class should allow it; a Vector3D subclass would
> be more natural for this.

That's the 'magic' good idea I'm looking for. I think a unified Vector
class for all size vectors is a worthy goal!

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


Re: Tricky Dictionary Question from newbie

2005-07-12 Thread James Carroll
Oops.. Gmail just normally puts the reply to at the bottom of the
discussion... so by default I reply to the list, and the last person
to post.  My comment was not directed at you.   I just posted the
contents of an interactive session that I did to better understand
setdefault myself.  I've got to remind myself to change the reply-to
address to the list.  (other lists do this by default, why not this
one?)

I agree that the name doesn't ring quite right to me either.

I kind of understand what the creator of the function was getting
at... it's kind of like when you want to retrieve a configuration
variable from a container, but if it's not there, then you want to use
a default:

storedWidth = container.GetConfigurationValue(name = "width", default=500)

If there is a width stored, it will retrieve that, otherwise it will
give you the default that you specified in the second parameter.  It
makes it easier than checking for existance,  then retrieving or
assigning a default.

Setdefault, in my mind is really a _get_ kind of operation.  It
retrieves from the dictionary most of the time, and only does anything
different when the key doesn't exist, and then does an assignment...

so my next guess at a better name for setdefault would be:

value = container.GetOrAddDefault(key="a", default=[])
value.append(listvalue)

but that's kind of confusing too, but it better describes what is happening.

-Jim

On 7/12/05, Peter Hansen <[EMAIL PROTECTED]> wrote:
> (Fixed top-posting)
> 
> James Carroll wrote:
>  > On 7/11/05, Peter Hansen <[EMAIL PROTECTED]> wrote:
>  >>(I always have to ignore the name to think about how it works, or it
>  >>gets in the way of my understanding it.  The name makes fairly little
>  >>sense to me.)
> 
> > Notice the dictionary is only changed if the key was missing.
> 
> James, I'll assume your reply was intended to address my comment above.
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing Something Simple

2005-07-12 Thread John Abel
harold fellermann wrote:

>Hi,
>
>  
>
>>I have a list of variables, which I am iterating over.  I need to set
>>the value of each variable.  My code looks like:
>>
>>varList = [ varOne, varTwo, varThree, varFour ]
>>
>>for indivVar in varList:
>>indivVar = returnVarFromFunction()
>>
>>However, none of the variables in the list are being set.
>>
>>
>
>You only change the value of the local variable in the body
>of the for loop. it has no effect on the list. you could do e.g.
>
>varList = [vorOne,varTwo,varThree,varFour]
>for i in len(varList) :
>   varList[i] = returnVarFromFunction()
>
>However, as in this example the former list values are not used anyway,
>you could just write:
>
>varList = [ returnVarFromFunction for i varList ]
>
>
>cheers,
>
>- harold -
>
>--
>Tages Arbeit, abends Gäste,
>saure Wochen, frohe Feste!
>-- Johann Wolfgang v. Goethe
>
>  
>
The problem I have, is the variables are referenced elsewhere.  They
have been declared before being used in the list.  Basically, I'm after
the Python way of using deferencing.

J

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


Re: Missing Something Simple

2005-07-12 Thread John Abel

>have been declared before being used in the list.  Basically, I'm after
>the Python way of using deferencing.
>  
>
OK, that should say dereferencing.

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


breaking out of nested loop

2005-07-12 Thread rbt
What is the appropriate way to break out of this while loop if the for
loop finds a match?

while 1:
for x in xrange(len(group)):
try:
mix = random.sample(group, x)
make_string = ''.join(mix)
n = md5.new(make_string)
match = n.hexdigest()
if match == target:
print "Collision!!!"
print make_string
Stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
print "Stop", Stop
break
else:
continue
except Exception, e:
print e 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing Something Simple

2005-07-12 Thread Thomas Guettler
Am Tue, 12 Jul 2005 14:44:00 +0100 schrieb John Abel:

> Hi,
> 
> I have a list of variables, which I am iterating over.  I need to set 
> the value of each variable.  My code looks like:
> 
> varList = [ varOne, varTwo, varThree, varFour ]
> 
> for indivVar in varList:
> indivVar = returnVarFromFunction()
> 
> However, none of the variables in the list are being set.  I thought of 
> using setattr, but this code sits in a function, and not class, so I'm 
> unsure what the object would be.

Hi,

"indivVar" is a *reference* to a value. You only change the
reference, not the value. Maybe this code helps you:

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

varList = [a, b, c]

for x in varList:
x = "foo"

# nothing changed
print varList # --> ["a", "b", "c"]

for i in range(len(varList)):
varList[i]="foo"

# List was changed
print varList # --> ["foo", "foo", "foo"]


HTH,
  Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: append one file to another

2005-07-12 Thread Steven D'Aprano
On Tue, 12 Jul 2005 06:47:50 -0700, [EMAIL PROTECTED] wrote:

> Hi,
> 
> I want to append one (huge) file to another (huge) file.

What do you call huge? What you or I think of as huge is not necessarily
huge to your computer.

> The current
> way I'm doing it is to do something like:
> 
> infile = open (infilename, 'r')
> filestr = infile.read()
> outfile = open(outfilename, 'a')
> outfile.write(filestr)
> 
> I wonder if there is a more efficient way doing this?

Why? Is it not working? Is it too slow? Does it crash your computer?

If you have any expectation that you code needs to run under Windows, or
cross-platform, or contains binary data, you should open your files in
binary mode:

infile = open(infilename, 'rb')
outfile = open(outfilename, 'ab')

For raw copying, you should probably use binary mode even if they just
contain text. Better safe than sorry...

Then, if you are concerned that the files really are huge, that is, as big
or bigger than the free memory your computer has, read and write them in
chunks:

data = infile.read(64)  # 64 bytes at a time is a bit small...
outfile.write(data)

Instead of 64 bytes, you should pick a more realistic figure, which will
depend on how much free memory your computer has. I suppose a megabyte is
probably reasonable, but you will need to experiment to find out.

Then when you are done, close the files:

infile.close()
outfile.close()

This is not strictly necessary, but it is good practice. If your program
dies, the files may not be closed properly and you could end up losing
data.


-- 
Steven.

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


Re: Yet Another Python Web Programming Question

2005-07-12 Thread Thomas Bartkus
"Daniel Bickett" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> It was his opinion that
> web programming should feel no different from desktop programming.


Should that ever become even remotely possible -

I'll be interested in web programming myself.
Thomas Bartkus


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


Re: Missing Something Simple

2005-07-12 Thread Fuzzyman
Hello John,

John Abel wrote:
> harold fellermann wrote:
>
> >Hi,
> >
> >
> >
> >>I have a list of variables, which I am iterating over.  I need to set
> >>the value of each variable.  My code looks like:
> >>
> >>varList = [ varOne, varTwo, varThree, varFour ]
> >>
> >>for indivVar in varList:
> >>indivVar = returnVarFromFunction()
> >>
> >>However, none of the variables in the list are being set.
> >>
> >>
> >
> >You only change the value of the local variable in the body
> >of the for loop. it has no effect on the list. you could do e.g.
> >
> >varList = [vorOne,varTwo,varThree,varFour]
> >for i in len(varList) :
> > varList[i] = returnVarFromFunction()
> >
> >However, as in this example the former list values are not used anyway,
> >you could just write:
> >
> >varList = [ returnVarFromFunction for i varList ]
> >
> >
> >cheers,
> >
> >- harold -
> >
> >--
> >Tages Arbeit, abends Gäste,
> >saure Wochen, frohe Feste!
> >-- Johann Wolfgang v. Goethe
> >
> >
> >
> The problem I have, is the variables are referenced elsewhere.  They
> have been declared before being used in the list.  Basically, I'm after
> the Python way of using deferencing.
>

The problem you have is that you don't understand the way that Python
references objects.

All Python names (aka variables) are references. You can rebind a name
to *any* object, but you can only change *some* objects. These are
called the mutable datatypes. The ones you can't changed are called
immutable types.

This is a common Python gotcha - but it's an integral part of the way
Python works - not a wart.

Your problem (I think) is that you have something like :

myVar = 'hello'
another_name = myVar
another_name = 'goodbye'
print myVar
   'hello'

but you expected 'goodbye'.

What you have done in the first line is created a new - a string with
the contents 'hello' - and bound the name

In the second line you bind another name to the *same* object. (You
*don't* bind the second name to the first name, but to the object it
references).

In the third line you create a new object and *rebind* the second name.
You haven't chanegd the underlying object. In Python the string is
immutable. This means it's hashable and can be used as a dictionary
key.

If you want to maintain a reference to a *location* then use a mutable
datatype. Instead of a list use a dictionary, keyed by name (as one
example).

e.g. a_dict = {'name1': object1, 'name2': object2}

Even if you change the contents of the dictionaries, the names will
still point to what you expect. (And you can still iterate over a
dictionary).

Before you get much further in Python you'll need a clearer
understanding of the difference between it's objects and names.

Best Regards,

Fuzzy
http://www.voidspace.org.uk/python

> J

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


question on "input"

2005-07-12 Thread [EMAIL PROTECTED]
Hi,

I want to accept the user's answer yes or no.
If I do this:

answer = input('y or n?')

and type y on the keyboard, python complains

Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 0, in ?
NameError: name 'y' is not defined

It seems like input only accepts numerals, or strings with quotes.
Need solutions, thanks.

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


Re: question on "input"

2005-07-12 Thread Bill Mill
On 12 Jul 2005 07:31:47 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I want to accept the user's answer yes or no.
> If I do this:
> 
> answer = input('y or n?')

Use raw_input instead:

>>> answer = raw_input("y or n?")
y or n?y
>>> answer
'y'

Check out the documentation of both functions at
http://docs.python.org/lib/built-in-funcs.html for more details.



Peace
Bill Mill
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software needed

2005-07-12 Thread Fuzzyman
Sounds like the sort of project that could work as a plugin to
chandler.

There's a Python interface to TWAIN (the scanner protocol) - but I'm
not *aware* of anything built on top of it. google may have a better
idea though.

Regards,

Fuzzy
http://www.voidspace.org.uk/python

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


Re: append one file to another

2005-07-12 Thread [EMAIL PROTECTED]
Thanks for the nice suggestions!

As a side question, you mentioned opening files in binary mode, in case
the code needs to run under Windows or cross-platform.  What would
happen otherwise?  Is it an issue of big little endian or some other
issue?

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


Re: question on "input"

2005-07-12 Thread Devan L
Use raw_input instead. It returns a string of whatever was typed. Input
expects a valid python expression.

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


Re: append one file to another

2005-07-12 Thread Steven D'Aprano
Dear me, replying to myself twice in one day...

On Wed, 13 Jul 2005 00:39:14 +1000, Steven D'Aprano wrote:

> Then, if you are concerned that the files really are huge, that is, as big
> or bigger than the free memory your computer has, read and write them in
> chunks:
> 
> data = infile.read(64)  # 64 bytes at a time is a bit small...
> outfile.write(data)

Sorry, that should be in a loop:

data = "anything"
while data:
data = infile.read(64)  # data will be empty when the file is read
outfile.write(data)

-- 
Steven.


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


Re: breaking out of nested loop

2005-07-12 Thread Fuzzyman
You either need to set a marker flag with multiple breaks - *or*
(probably more pythonic) wrap it in a try..except and raise an
exception. Define your own exception class and just trap for that if
you want to avoid catching other exceptions.

There is no single command to break out of multiple loops.

Regards,

Fuzzy
http://www.voidspace.org.uk/python

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


Re: Missing Something Simple

2005-07-12 Thread harold fellermann
>>> I have a list of variables, which I am iterating over.  I need to set
>>> the value of each variable.  My code looks like:
>>>
>>> varList = [ varOne, varTwo, varThree, varFour ]
>>>
>>> for indivVar in varList:
>>>indivVar = returnVarFromFunction()
>>>
>>> However, none of the variables in the list are being set.
>>>
>>
>> You only change the value of the local variable in the body
>> of the for loop. it has no effect on the list. you could do e.g.
>>
>> varList = [vorOne,varTwo,varThree,varFour]
>> for i in len(varList) :
>>  varList[i] = returnVarFromFunction()
>>
>> However, as in this example the former list values are not used 
>> anyway,
>> you could just write:
>>
>> varList = [ returnVarFromFunction for i varList ]
>>
> The problem I have, is the variables are referenced elsewhere.  They 
> have been declared before being used in the list.  Basically, I'm 
> after the Python way of using deferencing.

so, if I understand you right, what you want to have is a list of
mutable objects, whose value you can change without changing the 
objects'
references.

class Proxy :
def __init__(self,val) : self.set(val)
def set(self,val) : self.val = val
def get(self) : return self.val


a = Proxy(1)
b = Proxy(2)
c = Proxy(3)

varList = [a,b,c]

for i in varList :
i.set(returnVarFromFunction())

print a,b,c

prints whatever returnVarFromFunction has returned.
n.b.: instead of the Proxy class, you can use any other mutable
objects, e.g. lists.


- harold -


--
"All unsere Erfindungen sind nichts als verbesserte Mittel
  zu einem nicht verbesserten Zweck."
-- H.D. Thoreau

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


Help with inverted dictionary

2005-07-12 Thread rorley
I'm new to Python and I'm struggling.  I have a text file (*.txt) with
a couple thousand entries, each on their own line (similar to a phone
book).  How do I make a script to create something like an inverted
dictionary that will allow me to call "robert" and create a new text
file of all of the lines that contain "robert"?


Thanks so much.

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


Re: breaking out of nested loop

2005-07-12 Thread Peter Hansen
rbt wrote:
> What is the appropriate way to break out of this while loop if the for
> loop finds a match?

Define a flag first:

keepGoing = True

> while 1:
while keepGoing:

> for x in xrange(len(group)):
> try:
...
> if match == target:
> print "Collision!!!"
> print make_string

Set the flag here, then do the break:
   keepGoing = False

> break

Tada...

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


Re: append one file to another

2005-07-12 Thread Danny Nodal
Its been a while since I last coded in Python, so please make sure you test
it before trying it so you don't clobber your existing file. Although it may
not be more effecient than what you are doing now or has been suggested
already, it sure cuts down on the typing.

open(outfilename,'a').write(open(infilename).read())

Regards.

<[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>
> I want to append one (huge) file to another (huge) file.  The current
> way I'm doing it is to do something like:
>
> infile = open (infilename, 'r')
> filestr = infile.read()
> outfile = open(outfilename, 'a')
> outfile.write(filestr)
>
> I wonder if there is a more efficient way doing this?
> Thanks.
>


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


Re: breaking out of nested loop

2005-07-12 Thread rbt
Thanks guys... that works great. Now I understand why sometimes logic
such as 'while not true' is used ;)

On Tue, 2005-07-12 at 10:51 -0400, Peter Hansen wrote:
> rbt wrote:
> > What is the appropriate way to break out of this while loop if the for
> > loop finds a match?
> 
> Define a flag first:
> 
> keepGoing = True
> 
> > while 1:
> while keepGoing:
> 
> > for x in xrange(len(group)):
> > try:
> ...
> > if match == target:
> > print "Collision!!!"
> > print make_string
> 
> Set the flag here, then do the break:
>keepGoing = False
> 
> > break
> 
> Tada...
> 
> -Peter

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


Re: breaking out of nested loop

2005-07-12 Thread Duncan Booth
rbt wrote:

> What is the appropriate way to break out of this while loop if the for
> loop finds a match?
> 
> while 1:
> for x in xrange(len(group)):

another option not yet suggested is simply to collapse the two loops into a 
single loop:

import itertools

for x in itertools.cycle(range(len(group)):
   ... as before ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing Something Simple

2005-07-12 Thread John Abel
harold fellermann wrote:

>
>so, if I understand you right, what you want to have is a list of
>mutable objects, whose value you can change without changing the 
>objects'
>references.
>  
>
Yes!

>class Proxy :
>   def __init__(self,val) : self.set(val)
>   def set(self,val) : self.val = val
>   def get(self) : return self.val
>
>
>a = Proxy(1)
>b = Proxy(2)
>c = Proxy(3)
>
>varList = [a,b,c]
>
>for i in varList :
>   i.set(returnVarFromFunction())
>
>print a,b,c
>
>prints whatever returnVarFromFunction has returned.
>n.b.: instead of the Proxy class, you can use any other mutable
>objects, e.g. lists.
>
>
>- harold -
>
>
>--
>"All unsere Erfindungen sind nichts als verbesserte Mittel
>  zu einem nicht verbesserten Zweck."
>-- H.D. Thoreau
>
>  
>
That does it.  Thank you! 

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


Re: breaking out of nested loop

2005-07-12 Thread Steven D'Aprano
On Tue, 12 Jul 2005 10:19:04 -0400, rbt wrote:

> What is the appropriate way to break out of this while loop if the for
> loop finds a match?

Refactor it into something easier to comprehend?

And comments never go astray.


(Untested. And my docstrings are obviously bogus.)

def make_one_thing(group, x):
"""Makes a thing by plonking the frobber.
Expects group to be a list of foo and x to be an index.
"""
mix = random.sample(group, x)
make_string = ''.join(mix)
n = md5.new(make_string)
match = n.hexdigest()
return match

def group_matches(group, target):
"""Cycles over a group of foos, plonking the frobber of each
item in turn, and stopping when one equals target.
"""
for x in xrange(len(group)):
try:
match = make_one_thing(group, x)
if match == target:
return True
except Exception, e:
# don't stop just because the program has a bug
print e
# if we get here, there was no successful match after the 
# entire for loop
return False

def test_until_success:
"""Loop forever, or until success, whichever comes first.
"""
group = [1, 2, 3, 4]
target = 5
flag = False
while not flag:
print "No matches yet, starting to search..."
flag = group_matches(group, target)
# if we ever get here, it means we found a collision, and
# flag became True, so the while loop just dropped out
print "Collision!!!"
stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
print "Stopped at", stop



-- 
Steven.


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


Re: append one file to another

2005-07-12 Thread Grant Edwards
On 2005-07-12, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> As a side question, you mentioned opening files in binary
> mode, in case the code needs to run under Windows or
> cross-platform.  What would happen otherwise? Is it an issue
> of big little endian or some other issue?

The end-of-line characters might get converted -- even if
they're not really "end-of-line" characters in the file in
question.

-- 
Grant Edwards   grante Yow!  My mind is a potato
  at   field...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Why does reply to messages on this list put the sender in the To

2005-07-12 Thread Dark Cowherd
Most lists when i hit reply it puts the list address back in the To
address and some lists allow you to configure this.

But in this list reply sends the mail back as a private mail and there
seems to be no option to configure this.

Am I missing something
DarkCowherd
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with inverted dictionary

2005-07-12 Thread [EMAIL PROTECTED]
Hello,

First I'm not so clear about your problem, but you can do the following
steps:


1. Transform your file into list (list1)
2. Use regex to capture 'robert' in every member of list1 and add to
list2
3. Transform your list2 into a file

pujo

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


Re: Help with inverted dictionary

2005-07-12 Thread Devan L
import re
name = "Robert"
f = file('phonebook.txt','r')
lines = [line.rstrip("\n") for line in f.readlines()]
pat = re.compile(name, re.I)
related_lines = [line for line in lines if pat.search(line)]

And then you write the lines in related_lines to a file. I don't really
write text to files much so, um, yeah.

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


Re: breaking out of nested loop

2005-07-12 Thread Jeremy Sanders
rbt wrote:

> What is the appropriate way to break out of this while loop if the for
> loop finds a match?

queue discussion why Python doesn't have a "break N" statement...

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on Guido's ITC audio interview

2005-07-12 Thread Stephen Toledo-Brown
Tony Meyer wrote:

>>Everyone complaining about Eclipse in this thread needs to go 
>>try 3.1. The interface is much much much more responsive.
> 
> 
> The problem with Eclipse, IMO, is Java.  I've tried 3.1 on a WinXP machine
> and, like just about any Java program, it's incredibly slow and a real pain
> to use.  On a (similarly spec'd) Mac OS X Tiger machine, it runs nice and
> smoothly and is reasonably nice to use.  I'd happily recommend that Mac
> users try Eclipse, but never a Windows (Python) programmer.

I've not tried Mac, but under both Windows and Linux on x86, I find 
Eclipse (3.0) is slow with less than 1.25 GB of RAM, reasonably fast 
with 1.5GB or more. Processor speed and disk speed don't seem to be 
anywhere near as important.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: breaking out of nested loop

2005-07-12 Thread Tim Golden
[Jeremy Sanders]
| rbt wrote:
| 
| > What is the appropriate way to break out of this while loop 
| if the for
| > loop finds a match?
| 
| queue discussion why Python doesn't have a "break N" statement...



Presumably you meant "cue discussion..."



(Ducks & runs)
TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Help with inverted dictionary

2005-07-12 Thread rorley
OK, so my problem is I have a text file with all of these instances,
for example 5000 facts about animals.  I need to go through the file
and put all of the facts (lines) that contain the word lion into a file
called lion.txt.  If I come across an animal or other word for which a
file does not yet exist I need to create a file for that word and put
all instances of that word into that file.  I realize that this should
probably create 30,000 files or so.  Any help would be REALLY
appreciated.  Thanks.  Reece

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


Re: breaking out of nested loop

2005-07-12 Thread Andrew Koenig
"rbt" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> What is the appropriate way to break out of this while loop if the for
> loop finds a match?

Make it a function and use a "return" statement to break out.


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


Web client, https and session management

2005-07-12 Thread Yannick Turgeon
Hello all,

2-3 years ago, I did a program in perl. Now I have to modify it and I
want to rewrite it from scratch using Python.

The program is doing this:
1- Load Yahoo login webpage (https)
2- Log into Yahoo website using my personal login and password.
3- Grasp and extract some information from my mailing lists messages
(http, not https).

My questions are:
- Is it possible to do this using Python?
- How?

To acheive point #3, which is the goal, my web client has to manage
session (because of the login aspect). This is the part I don't know
how it's working. Any help would be appreciated. Thanks.

Yannick

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


Re: Creating anonymous functions using eval

2005-07-12 Thread Devan L
How is this different from a nested function?

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


Re: Why does reply to messages on this list put the sender in the To

2005-07-12 Thread Peter Decker
On 7/12/05, Dark Cowherd <[EMAIL PROTECTED]> wrote:

> Most lists when i hit reply it puts the list address back in the To
> address and some lists allow you to configure this.
> 
> But in this list reply sends the mail back as a private mail and there
> seems to be no option to configure this.
> 
> Am I missing something

Nope, it's a preference set by the list managers. There are two
distinct POVs on this subject, and the feeling is pretty intense on
both sides. Here are two summaries:

Reply to sender: http://www.unicom.com/pw/reply-to-harmful.html
Reply to list: http://www.blackgate.net/consulting/reply-to_munging_useful.html

IMO, the various purist postions are meaningless drivel by people more
concerned with following a ideal notion instead of being concerned
with how the software is actually used. If you think in those terms,
replies to discussion lists should go to the list, and replies to
announcement-type lists should go to the sender.

In cases where people are discussing problems and supplying solutions,
replying to the list is essential so that as many people as possible
can benefit from the knowledge contained in the reply. Private replies
only benefit the lone recipient, while list replies benefit everyone
on the list and everyone who later searches the archives.

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with inverted dictionary

2005-07-12 Thread Devan L
I think you need to get a database. Anyways, if anything, it should
create no more than 5,000 files, since 5,000 facts shouldn't talk about
30,000 animals. There have been a few discussions about looking at
files in directories though, if you want to look at those.

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


Re: Web client, https and session management

2005-07-12 Thread Grant Edwards
On 2005-07-12, Yannick Turgeon <[EMAIL PROTECTED]> wrote:

> To acheive point #3, which is the goal, my web client has to manage
> session (because of the login aspect). This is the part I don't know
> how it's working.

You might want to take a look at the ClientCookie package.

-- 
Grant Edwards   grante Yow!  Then, it's off to
  at   RED CHINA!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with inverted dictionary

2005-07-12 Thread rorley
I will transfer eventually use a database but is there any way for now
you could help me make the text files?  Thank you so much.  Reece

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


Re: Help with inverted dictionary

2005-07-12 Thread rorley
I will transfer eventually use a database but is there any way for now
you could help me make the text files?  Thank you so much.  Reece

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


Re: Help with inverted dictionary

2005-07-12 Thread rorley
I will transfer eventually use a database but is there any way for now
you could help me make the text files?  Thank you so much.  Reece

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


Re: Help with inverted dictionary

2005-07-12 Thread Devan L
Oh, I seem to have missed the part saying 'or other word'. Are you
doing this for every single word in the file?

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


Issues With Threading

2005-07-12 Thread Your Friend
Hello All,

I'm having issues capturing the output from a program while using
threading.  Program runs ok when I run without threading.  Here's my
Python code and the Java class that is called by it.

Python :

#!/usr/bin/python

import popen2
import threading

for id in range( 10 ) :
( err_out, stdin ) = popen2.popen4( ( '/usr/bin/java JavaTest
%s' ) % ( id ) )
for line in err_out.readlines() :
print line,

def test( id ) :
print "Called %s" % ( id )
( err_out, stdin ) = popen2.popen4( ( '/usr/bin/java JavaTest
%s' ) % ( id ) )
for line in err_out.readlines() :
print line,

#for id in range( 10 ) :
#thread = threading.Thread( target=test, args=( [ id ] ) )
#thread.start()

Java :

import java.util.Date;

public class JavaTest {
public static void main( String args[] ) {
System.out.println( args[0] + " - " + new
Date().toString() );
}
}

When I run without threading, I get the correct output :

0 - Tue Jul 12 11:33:51 EDT 2005
1 - Tue Jul 12 11:33:52 EDT 2005
2 - Tue Jul 12 11:33:52 EDT 2005
3 - Tue Jul 12 11:33:53 EDT 2005
4 - Tue Jul 12 11:33:53 EDT 2005
5 - Tue Jul 12 11:33:54 EDT 2005
6 - Tue Jul 12 11:33:54 EDT 2005
7 - Tue Jul 12 11:33:54 EDT 2005
8 - Tue Jul 12 11:33:54 EDT 2005
9 - Tue Jul 12 11:33:54 EDT 2005

When I uncomment the threading section and run again, I see that the
function is called, but the result from the Java code does not get
printed :

Called 0
Called 1
Called 2
Called 3
Called 4
Called 5
Called 6
Called 7
Called 8
Called 9

I hope this is just a nuance that I've run across and it's an easy
solution ... any advice pointing me in the right direction would be
greatly appreciated.

Thanks

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


Re: Help with inverted dictionary

2005-07-12 Thread rorley
Yes, I am.  Does that make it harder.

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


Re: Software needed

2005-07-12 Thread Peter Herndon
"Document Management Software" is a little vague.  What do you want it
to do?  In general though, when someone says "content management" and
"Python", the general response is Zope, usually with Plone on top.

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


automatic form filling

2005-07-12 Thread ulrice jardin
hi,

I would like to know how I could automatically fill a
(search) form on a web page and download the resulting
html page. More precisely I would like to make a
program that would automatically fill the "Buscador
lista 40" (in spanish, sorry) form in the following
webpage:
http://www.los40.com/actualidad/listas/lista40.html
and download the results for several dates
(dia/mes/año = day/month/year).
I am not sure this is the right place to ask, but I
would be very grateful if anybody can help or redirect
me to another mailing list...
thx
jul

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Should I use "if" or "try" (as a matter of speed)?

2005-07-12 Thread Dark Cowherd
I use Delphi in my day job and evaluating and learning Python over the
weekends and spare time. This thread has been very enlightening to me.

The comments that Joel of Joel on Software makes here
http://www.joelonsoftware.com/items/2003/10/13.html was pretty
convincing. But I can see from the comments made by various people
here that since Python uses Duck typing and encourages typless styles
of functions exceptions may actually be the better way to go.

But one advise that he gives which I think is of great value and is
good practice is
"Always catch any possible exception that might be thrown by a library
I'm using on the same line as it is thrown and deal with it
immediately."

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


Re: append one file to another

2005-07-12 Thread Steven D'Aprano
On Tue, 12 Jul 2005 07:38:39 -0700, [EMAIL PROTECTED] wrote:

> Thanks for the nice suggestions!
> 
> As a side question, you mentioned opening files in binary mode, in case
> the code needs to run under Windows or cross-platform.  What would
> happen otherwise?  Is it an issue of big little endian or some other
> issue?

No, nothing to do with big and little endian issues. It is all to do with
the line delimiter, and possibly the end-of-file marker.

Windows uses '\r\n' as the line delimiter for text files. (Or is it
'\n\r'? I always forget...)

Old-style Macintosh used '\r', and (almost) everything else, including new
Macs running OS X, uses '\n'.

If you open files in text mode, there can be complications due to the
different line endings. To be perfectly frank, I only use Python under
Linux, so I don't have the foggiest idea of just what Bad Things can
happen. I know it is a big problem when using some FTP programs, which
have a tendency to destroy binary programs if you upload/download them in
text mode. 

I just did some experiments here, and can't get anything bad to happen.
But whatever the problem is, my grand-pappy always told me, open the
danged file in binary mode and you can't go wrong.

*wink*

I have found some discussions here:

http://python.active-venture.com/tut/node9.html

"Windows makes a distinction between text and binary files; the
end-of-line characters in text files are automatically altered slightly
when data is read or written. This behind-the-scenes modification to file
data is fine for ASCII text files, but it'll corrupt binary data like that
in JPEGs or .EXE files. Be very careful to use binary mode when reading
and writing such files."

and here:

http://zephyrfalcon.org/labs/python_pitfalls.html

This website recommends:

"Solution: Use the correct flags -- 'r' for text mode (even on Unix), 'rb'
for binary mode."

but I've never had any problems using 'rb' for text files under Linux.

I'm also told that Windows uses ctrl-Z as the end-of-file marker, and if
it finds that character in the middle of a text file, it will assume the
file has finished and stop reading. But only in text mode, not binary. I
don't think that's a problem for Linux.


-- 
Steven.

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


Re: Tricky Dictionary Question from newbie

2005-07-12 Thread Tim Peters
[Peter Hansen]
...
> I suppose I shouldn't blame setdefault() itself for being poorly named,

No, you should blame Guido for that .

> but it's confusing to me each time I see it in the above, because the
> name doesn't emphasize that the value is being returned, and yet that
> fact is arguably more important than the fact that a default is set!
>
> I can't think of a better name, though, although I might find "foo" less
> confusing in the above context. :-)

I wanted to call it getorset() -- so much so that even now I sometimes
still type that instead!  The "get" part reminds me that it's fetching
a value, same as dict.get(key, default) -- "or set"'ing it too if
there's not already a value to "get".  If you have a fancy enough
editor, you can teach it to replace setdefault by getorset whenever
you type the former ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >