mass editing for keys in a dictionary

2007-09-14 Thread james_027
hi,

How could I transform something like this

dict_1 = {'customer_id':1, 'item_id':3, amount:100}

into

dict_2 = {'customer':1, 'item':3, amount:100}

thanks
james

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


Re: "once" assigment in Python

2007-09-14 Thread Steve Holden
Lorenzo Di Gregorio wrote:
> Hello,
> 
> I've been using Python for some DES simulations because we don't need
> full C speed and it's so much faster for writing models.  During
> coding I find it handy to assign a variable *unless it has been
> already assigned*: I've found that this is often referred to as "once"
> assigment.
> 
> The best I could come up with in Python is:
> 
> try:
>   variable
> except NameError:
>   variable = method()
> 
> I wonder if sombody has a solution (trick, whatever ...) which looks
> more compact in coding.  Something like:
> 
> once(variable, method)
> 
> doesn't work, but it would be perfect.  Of course I can preprocess the
> Python code but an all-Python solution would be more handy.
> 
> Any suggestions?
> 
Without being fatuous, I would suggest you rethink your approach to the 
problem.

Do your variables have default values? If not, what happens if the user 
does not set them and your code tries to refer to them? You seem to be 
trying to apply defaults if the user hasn't set a value, when the 
correct things to do is to apply the defaults *before the user gets a 
chance to do anything at all*. Then any changes made by the user will 
overwrite the defaults.

Even better, if its practical, is to provide your functionality as one 
or more functions, whose definitions can set default values for keyword 
arguments.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline

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


Re: Spaces from string specifier

2007-09-14 Thread Gabriel Genellina
En Fri, 14 Sep 2007 01:57:43 -0300, Gavin Tomlins <[EMAIL PROTECTED]>  
escribi�:

> I'm trying to work out when using a format specifier I get spaces in the
> resulting string.  Eg. Looking at the outputted string you can see that
> there are spaces after T5LAT, F4LAT etc. as I result from trying to keep  
> the
> code aligned

- You should *not* build the SQL text yourself; use a parametrised query  
instead. It's not only easier to write; it's safer, less error prone, and  
maybe faster. See this previous post  


- Spaces are not significant in SQL, but you may have your own reasons to  
format the SQL text in a certain way. In addition to the ideas already  
menctioned on that thread (avoid \, use parenthesis, and auto-concatenate  
adjacent strings), you may use a triple-quoted string + function dedent  
 from textwrap module:

py> fmtSqlP300Amp = textwrap.dedent('''\
...   UPDATE Patient SET
... O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s",
... P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s",
... TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s"
...   WHERE Pat_Id = "%s"''')
py> print fmtSqlP300Amp
UPDATE Patient SET
   O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s",
   P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s",
   TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s"
WHERE Pat_Id = "%s"

I hope any of these ideas will fit your own needs.

-- 
Gabriel Genellina

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

Re: mass editing for keys in a dictionary

2007-09-14 Thread Amit Khemka
On 9/14/07, james_027 <[EMAIL PROTECTED]> wrote:
> hi,
>
> How could I transform something like this
>
> dict_1 = {'customer_id':1, 'item_id':3, amount:100}
>
> into
>
> dict_2 = {'customer':1, 'item':3, amount:100}

A one liner would be :

>>> dict_2 = dict([(k.split('_')[0], v) for (k,v) in dict_1.iteritems()])

It would split the keys by '_' and use first part of split as the new key !

You must be aware be careful in cases where there are keys like
'customer_1' , 'customer_2', ...

Cheers,


-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
-- 
http://mail.python.org/mailman/listinfo/python-list


funny little 190 lines command line math tutor I wrote for my 7-year old.

2007-09-14 Thread DouhetSukd
Sadly lacking in multi-media bells and whistles.  But my daughter
actually likes playing with it.

Coded on windows, but no reason it shouldn't work on Linux/OS X.

(hopefully the indentation won't be too mangled by usenet.  apologies
in advance if that is the case)

Enjoy.

Sample session:

D:\user\python>mathtester.py -1 3 -o /+ -r 2
Hello, I am your friendly computer.  I have a math quiz for you

 Problem #1

 1 +  2 = 3
Answered: 3.  Correct.

 Problem #2

 3 +  3 = 6
Answered: 6.  Correct.


Congratulations, you got  2 right out of  2


code:


"""
mathtester.py -h for more help .

HELPS YOUR KIDS TO LEARN MATH WITH INTERACTIVE PROMPTS.  EXAMPLE:

Hello, I am windoze, your friendly computer.  I have a math quiz for
you

 Problem #0

 4 -  3 = 1
Answered: 1.  Correct.

 Problem #1

 8 -  6 = 14
Answered:14.  Wrong.  Correct
answer: 2

This will pick two numbers, each between 0 and 10.  It will either add
or substract them.  Any questions with solutions less than zero
or greater than 20 will be rejected and re-created.

You get this by running it with all defaults.  i.e.

c:\>python mathtester.py


to get something like doing the multiplication of 1 to 3 times 10, run

c:\>python mathtester -o * -1 3 -2 10 -H 30

only multiplication '*' will be used, number #1 will be between 0 and
3.  number #2 will be between 0 and 10.  answers greater than 30 will
be rejected.

"""

import os, sys, optparse, random

_module_doc = __doc__

class Writer:
"""write to file and output to console"""
def  __init__(self,fout):
self.fout = fout
def __call__(self,s,echoconsole=True):
self.fout.write("\n" + s.replace("\t",""))
if echoconsole:
print s

class Worker:

fout = None
filename = "test.txt"
trivial_tolerance_percentage = 40
accepted_operators = "+-*"

def formatoptions(self):
"""most of the work is already done by optparser"""
#filter on acceptable operators.  exit if none found.
self.operators = [i for i in self.options.operators if i in
self.accepted_operators]
if not self.operators:
print ERROR_MSG_OPERATORS % {"supported" :
self.accepted_operators}
sys.exit()
#both number range limits are equal.
if not self.options.numberRange2:
self.options.numberRange2 = self.options.numberRange


def  __init__(self):
self.fout = open(self.filename,"w")
Worker.writer = Writer(self.fout)
self.formatoptions()
self.asked = self.correct = 0
self.set_asked = set()

def process(self):
"""main loop - prints greetings, loops on questions, print
result summary and exits"""
try:
  self.writer(GREETING)
  [self.doTest(cntr) for cntr in
range(0,self.options.repetitions)]
except KeyboardInterrupt:
  pass
self.writer(FAREWELL % vars(self))
return True

def doTest(self,number):
"""the workhorse function.  randomly picks a question + vets
the solution
then asks the question and checks the answer"""
self.writer("\n Problem #%s" % (number+1))

while True:
#pick random numbers and operator
number1  = random.randint(0,self.options.numberRange)
number2  = random.randint(0,self.options.numberRange2)
operator =
self.operators[random.randint(0,len(self.operators)-1)]

if number1 < 2 or number2 < 2 and
random.randint(1,100)>self.trivial_tolerance_percentage:
#potentially reject trivial problems consisting of
zeros and ones.
continue

#flip a coin and put number #1 either right or left -
#remember that the number ranges can be unequal so there
is a difference
if random.randint(1,2) % 2:
problem  = "%2s %s %2s" % (number1,operator,number2)
else:
problem  = "%2s %s %2s" % (number2,operator,number1)

#use eval to get the expected solution
solution = eval(problem)

#solution within accepted bounds? if not, build another
problem
if not ((solution >= self.options.minSolution) and
(solution <= self.options.maxSolution)):
continue

#don't ask the same question multiple times...
if problem in self.set_asked:
continue
self.set_asked.add(problem)

#answers other than digits will be ignored and the prompt
will repeat
while True:
try:
prompt = "\n\t\t" + problem + " = "
self.writer(prompt,False)
answer = raw_input(prompt)

Re: An ordered dictionary for the Python library?

2007-09-14 Thread Mark Summerfield
On 14 Sep, 02:35, Jürgen Urner <[EMAIL PROTECTED]> wrote:
> Puh, what a discussion... most common use case I can think of is
>
> >> d = {'a': 1, 'b': 2, 'c': 3}
> >> for key in d:
> >> # do something that relies on order of keys as specified in the 
> >> constructor
>
> It's a bit tireing having to type
>
> >> for key in sorted(d.keys()):
> >> do_somethig_with(d[key])
>
> instead of a trustfully
>
> >> for value in d.values():
> >> do_somethig_with(value)
>
> As far as I can see much cleaner. No black magic needed ++ sort the
> dict
> to another order and rely on the sort order being stable would be a
> really
> a nice thing to have.
>
> My 2 cents,  Jürgen

What I envisage is:

d = ordereddict(a=1, x=20, b=35, m=4)
# some time later
d["e"] = 15
# later still
d["b"] = 70
d.keys() # returns ['a', 'b', 'e', 'm', 'x']
d.values() # returns [1, 70, 15, 4, 20]

So no matter _when_ you add because the underlying data structure is
ordered (by key) you can always get access in key order. Also, you
can't "sort" the ordereddict; it is in key order and that's it. The
whole point is that you can use these things and never have to sort;
if you need different orders you create extra ordereddicts with
suitably munged keys and with values that are object references to the
objects you are interested in.

In reply to James Stroud:

- The reason you can't assign a slice is that the index positions
depend on the keys, so if you do:
od[newkey] = newvalue
where newkey goes (i.e., its index position) depends on how it orders
in relation to the rest, so it could go "anywhere".
I now feel that offering a slice is wrong because the [] syntax is
used for access by key, whereas a slice would be for access by index,
so using [] for both would be v. confusing.

- James proposed better method names which I've adopted (see later),
but I don't think set_value() should be set() because that would make
it seem to be the partner of get(), whereas get() uses a key and
set_value() uses an index for lookup.

- James also suggested a name and behaviour change:

keys(fromindex : int = None, uptobutexcludingindex : int = None) -
> ordered list of keys

So keys() called on its own behaves just like dict.keys() (except that
all the keys are returned in order), but with one argument returns the
keys with index positions from the given index to the end, and with
two arguments returns the keys in the given range of indexes. (Note:
in an ordereddict values() returns all the values in key order.)

So from the earlier example:

d.key(2) # returns 'e'
d.item(3) # returns ('m', 4)
d.value(4) # returns 20
d.set_value(3, 99) # maybe returns 'm'; but anyway d.value(3) and
d['m'] now both return 99

- James (and some others) also felt that insertions should just go as
key/value pairs at the end. But that is not what I'm proposing (that's
a completely different data structure).

The whole point of ordereddict is that whatever you insert and
whenever you insert it, the ordereddict is always in key order.

Paul Rubin and at least one other person mentioned the use of an AVL
tree. At the moment I just want to see if I can get enough consensus
on an API and behaviour so that I could put in a PEP for just one
ordered data structure.

So to clarify, here's the entire API I'm proposing for ordereddict. In
all cases the ordereddict is always in (and kept in) key order, and
any method that returns a list or iterator always returns that list or
iterator (whether of keys or values) in key order:

ordereddict(dictionary=None)
The argument can be a dict or another ordereddict; all the dict()
initializer
approaches should also be supported.

ordereddict.update(dictonary=None, **kwargs)
Same as dict.update()---except that key order is preserved (a
point I won't
repeat in the others when I say "same as dict", but which is true
throughout)

@classmethod
ordereddict.fromkeys(cls, iterable, value=None) # Same as dict

ordereddict.key(index : int) -> key
Returns the index-th item's key

ordereddict.item(index : int) -> (key, value)
Returns the index-th item

ordereddict.value(index : int) -> value
Returns the index-th item's value

ordereddict.set_value(index : int, value)
Sets the index-th item's value to value; raises IndexError if
index is out of
range. If not expensive, maybe return the key.

ordereddict.copy() # Same as dict.
ordereddict.clear() # Same as dict.
ordereddict.get(key, value=None) # Same as dict
ordereddict.setdefault(key, value) # Same as dict
ordereddict.pop(key, value) # Same as dict
ordereddict.popitem() # Same as dict

ordereddict.keys(fromindex : int = None, uptoindex : int : None) ->
list of keys
Returns an ordered list of keys, or a slice of keys if one or two
indexes is given

ordereddict.values() # Same as dict
ordereddict.items() # Same as dict
ordereddict.iterkeys() # Same as dict
ordereddict.itervalues() # Same as dict
ordereddict.iteritems() # Same as dict
ordereddict.has_key() # Same as dict

Re: Python 3K or Python 2.9?

2007-09-14 Thread Bruno Desthuilliers
Bjoern Schliessmann a écrit :
> Bruno Desthuilliers wrote:
>> Bjoern Schliessmann a écrit :
> 
>>> Why don't you make a preprocessor which accepts method
>>> declarations without "self" and fixes them?
>> The problem being that there's no such thing as a "method
>> declaration" in Python 
> 
> Yep, there are only definitions. I'm sorry.
> 
>> - only functions being attributes of a class...
> 
> What, IYHO, is the difference between a method and a function?

A method is a thin wrapper around a function, usually instanciated and 
returned by the __get__ method [1] of the function itself when the 
function is looked up as an attribute of a class or an instance:

 >>> class Foo(object):
... def meth(self):
... print "in %s meth" % self
...
 >>> Foo.__dict__['meth']

 >>> Foo.meth

 >>> Foo().meth
>
 >>>

[1] you may want to read about the descriptor protocol which is the base 
mechanism on which methods and properties (computed attributes) are based.

>> (ok, I know, you meant "functions declared within a class
>> statement").
> 
> I think that those functions _are_ special ones

They aren't, and you should perhaps read the manual - all this is 
documented.

> since the compiler
> is able to make "method(instance, a, b)" out of 
> "instance.method(a, b)".

Once again, the compiler has *nothing* to do with this. Else, how could 
you do this:

 >>> def fun(obj):
... print obj
...
 >>> Foo.fun = fun
 >>> Foo.fun

 >>> Foo().fun
>
 >>> fun

 >>> Foo.__dict__['fun']

 >>>


> So IMHO, "method definition" makes sense.

It doesn't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: funny little 190 lines command line math tutor I wrote for my 7-year old.

2007-09-14 Thread DouhetSukd
Ok, it does look a bit mangled.  I re-posted it on www.pastebin.com,
at http://python.pastebin.com/m7b1f9ab5.

Cheers

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


Re: mass editing for keys in a dictionary

2007-09-14 Thread Bruno Desthuilliers
james_027 a écrit :
> hi,
> 
> How could I transform something like this
> 
> dict_1 = {'customer_id':1, 'item_id':3, amount:100}
> 
> into
> 
> dict_2 = {'customer':1, 'item':3, amount:100}

dict_2 = dict((k[:-3], v) for k, v in dict_1.iteritems())
-- 
http://mail.python.org/mailman/listinfo/python-list


calculate matrik

2007-09-14 Thread susanti marsol
how to calculate the matrik? can u  give me the sintax code?
thanks so much before.

   
-
Be a better Globetrotter. Get better travel answers from someone who knows.
Yahoo! Answers - Check it out.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: "once" assigment in Python

2007-09-14 Thread DouhetSukd
Agree that what you are looking for may not be a good idea.  So make
sure you don't shoot yourself in the foot with it.  You should
probably look into your problem some more.

>>> def once(obj,attrname,value):
... if hasattr(obj,attrname):
... return
... else:
... setattr(obj,attrname,value)
...
>>> class Foo:
... pass
...
>>> foo = Foo()
>>> once(foo,"a",1)
>>> foo.a
1
>>> once(foo,"b",2)
>>> foo.a
1
>>> def m1(self):
... print "i am m1"
...
>>> def m2(self):
... print "i am m2"
...
>>> once(Foo,"mx",m1)
>>> foo.mx()
i am m1
>>> once(Foo,"mx",m2)
>>> foo.mx()
i am m1
>>>

This is very generic code, but you could make it specific to a class
and an attribute.  If so look into properties.

class Foo2:

  def _setMyAttr(self,value):
 if hasattr(self,"_myAttr"):
   return
 self._myAttr = value

  def _getMyAttr(self):
 if not hasattr(self,"_myAttr"):
return "somedefaultvalue"
 return self._myAttr

  myAttr = property(_getMyAttr,_setMyAttr)

Note also :  stay away from __setattr__ until you know what you are
doing and
you know when to use self.__dict__ assignments.  Painful personal
experiences for me.

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


Re: "once" assigment in Python

2007-09-14 Thread Peter Otten
Lorenzo Di Gregorio wrote:

> I've been using Python for some DES simulations because we don't need
> full C speed and it's so much faster for writing models.  During
> coding I find it handy to assign a variable *unless it has been
> already assigned*: I've found that this is often referred to as "once"
> assigment.
> 
> The best I could come up with in Python is:
> 
> try:
>   variable
> except NameError:
>   variable = method()
> 
> I wonder if sombody has a solution (trick, whatever ...) which looks
> more compact in coding.  Something like:
> 
> once(variable, method)
> 
> doesn't work, but it would be perfect.  Of course I can preprocess the
> Python code but an all-Python solution would be more handy.
> 
> Any suggestions?

You can use properties to implement lazy evaluation. Or you can rely on a
naming convention:

>>> class Once(object):
... def __getattr__(self, name):
... if name.startswith("_calc_"):
... raise AttributeError("No method to calculate attribute 
%r" % name[6:])
... value = getattr(self, "_calc_" + name)()
... setattr(self, name, value)
... return value
... 
>>> class A(Once):
... def _calc_foo(self):
... print "calculating foo"
... return 42
... 
>>> a = A()
>>> a.foo
calculating foo
42
>>> a.foo
42
>>> a.bar
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in __getattr__
  File "", line 4, in __getattr__
AttributeError: No method to calculate attribute 'bar'
>>> a._calc_bar = lambda: "bar-value"
>>> a.bar
'bar-value'

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


Re: "once" assigment in Python

2007-09-14 Thread Carl Banks
On Fri, 14 Sep 2007 06:16:56 +, Lorenzo Di Gregorio wrote:

> Hello,
> 
> I've been using Python for some DES simulations because we don't need
> full C speed and it's so much faster for writing models.  During coding
> I find it handy to assign a variable *unless it has been already
> assigned*: I've found that this is often referred to as "once"
> assigment.

I could see reasons for doing something like this at a module level or 
for attributes; such as setting default values when defaults are 
expensive to calculate.  You could, as others have said, initialize the 
variable to a trivial value and then test whether it still held the 
trivial value later, but what's the point?


> The best I could come up with in Python is:
> 
> try:
>   variable
> except NameError:
>   variable = method()
> 
> I wonder if sombody has a solution (trick, whatever ...) which looks
> more compact in coding.  Something like:
> 
> once(variable, method)
> 
> doesn't work, but it would be perfect.

For module level variables you can do something like this:

def once(symbol,method):
g = globals()
if symbol not in g:
g[symbol] = method() 

You'd have to pass a symbol as a string, but that's no big deal.

For local variables you're stuck with trying to catch UnboundLocalError.  
There's a way to do it by examining stack frames, but I don't really 
recommend it: it's inefficient, and the once assignment doesn't make as 
much sense for local variables.



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


Re: lxml + mod_python: cannot unmarshal code objects in restricted execution mode

2007-09-14 Thread Dmitri Fedoruk
On Sep 14, 3:04 am, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> Try forcing mod_python to run your code in the first interpreter
> instance created by Python.
>   PythonInterpreter main_interpreter
Thank you very much, that solved the problem! A more detailed
discussion can also be found in the lxml-dev mailing list (
http://comments.gmane.org/gmane.comp.python.lxml.devel/2942 )

Dmitri

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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Mark Summerfield
I forgot one item in the proposed API:

ordereddict.delete(index : int)

Also, the API for keys() should be

ordereddict.keys(firstindex : int = None, secondindex : int = None)

If called with no args, returns list of all keys (in key order of
course); if one arg is given, returns keys with indexes in range(0,
firstindex); if two args are given, returns keys with indexes in
range(firstindex, secondindex).

Below is a stripped-down implementation in pure python that is just 84
lines long.
(I have a proper version with blank lines and doctests which is 482
lines but I thought that was a bit long to post.)

It should work as a drop-in replacement for dict (apart from
performance), but with the keys ordered by <, so that every list or
iterator that it returns is always in key order.

The get(), has_key(), __contains__(), len(), and __getitem__() methods
are not reimplemented because the base class versions work fine.

I'm only posting it to give a better feel for the API---if someone did
a better (faster) implementation (e.g., in C), that'd be great, but
best to get consensus on an API first I think (if consensus is
possible at all!).

import bisect
class ordereddict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__keys = sorted(dict.keys(self))
def update(self, *args, **kwargs):
dict.update(self, *args, **kwargs)
self.__keys = sorted(dict.keys(self))
@classmethod
def fromkeys(cls, iterable, value=None):
dictionary = cls()
for key in iterable:
dictionary[key] = value
return dictionary
def key(self, index):
return self.__keys[index]
def item(self, index):
key = self.__keys[index]
return key, self[key]
def value(self, index):
return self[self.__keys[index]]
def set_value(self, index, value):
self[self.__keys[index]] = value
def delete(self, index):
key = self.__keys[index]
del self.__keys[index]
dict.__delitem__(self, key)
def copy(self):
dictionary = ordereddict(dict.copy(self))
dictionary.__keys = self.__keys[:]
return dictionary
def clear(self):
self.__keys = []
dict.clear(self)
def setdefault(self, key, value):
if key not in self:
bisect.insort_left(self.__keys, key)
return dict.setdefault(self, key, value)
def pop(self, key, value=None):
if key not in self:
return value
i = bisect.bisect_left(self.__keys, key)
del self.__keys[i]
return dict.pop(self, key, value)
def popitem(self):
item = dict.popitem(self)
i = bisect.bisect_left(self.__keys, item[0])
del self.__keys[i]
return item
def keys(self, firstindex=None, secondindex=None):
if firstindex is not None and secondindex is None:
secondindex = firstindex
firstindex = 0
else:
if firstindex is None:
firstindex = 0
if secondindex is None:
secondindex = len(self)
return self.__keys[firstindex:secondindex]
def values(self):
return [self[key] for key in self.__keys]
def items(self):
return [(key, self[key]) for key in self.__keys]
def __iter__(self):
return iter(self.__keys)
def iterkeys(self):
return iter(self.__keys)
def itervalues(self):
for key in self.__keys:
yield self[key]
def iteritems(self):
for key in self.__keys:
yield key, self[key]
def __delitem__(self, key):
i = bisect.bisect_left(self.__keys, key)
del self.__keys[i]
dict.__delitem__(self, key)
def __setitem__(self, key, value):
if key not in self:
bisect.insort_left(self.__keys, key)
dict.__setitem__(self, key, value)
def __repr__(self):
return "ordereddict({%s})" % ", ".join(
   ["%r: %r" % (key, self[key]) for key in self.__keys])

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


Just bought Python in a Nutshell

2007-09-14 Thread Lamonte Harris
http://www.powells.com/biblio/63-9780596001889-7  Used, has anyone read this
book.  Any additional information that you like,dislike about this book? [I
like having real books and stead of ebooks because its better on the eyes.]
Should be her 2morrow Afternoon :), few hours before I get home great deal
:D.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: newbie: self.member syntax seems /really/ annoying

2007-09-14 Thread Bjoern Schliessmann
stef mientki wrote:
> Indeed, so I wondered why there isn't open source alternative (at
> least I didn't find one).

Have a look at scilab and octave. Not sure if it's GPL though.

Regards,


Björn

-- 
BOFH excuse #387:

Your computer's union contract is set to expire at midnight.

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


Re: extract text from log file using re

2007-09-14 Thread Peter Otten
Fabian Braennstroem wrote:

> I would like to delete a region on a log file which has this
> kind of structure:
> 
> 
> #--flutest
>498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04
> 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01  499
>499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04
> 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01  499
> reversed flow in 1 faces on pressure-outlet 35.
> 
> Writing
> "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.cas"...
>  5429199 mixed cells, zone 29, binary.
> 11187656 mixed interior faces, zone 30, binary.
>20004 triangular wall faces, zone 31, binary.
> 1104 mixed velocity-inlet faces, zone 32, binary.
>   133638 triangular wall faces, zone 33, binary.
>14529 triangular wall faces, zone 34, binary.
> 1350 mixed pressure-outlet faces, zone 35, binary.
>11714 mixed wall faces, zone 36, binary.
>  1232141 nodes, binary.
>  1232141 node flags, binary.
> Done.
> 
> 
> Writing
> "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.dat"...
> Done.
> 
>500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04
> 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10  500
> 
>  reversed flow in 2 faces on pressure-outlet 35.
>501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04
> 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01  499
> 
> #--
> 
> I have a small script, which removes lines starting with
> '(re)versed', '(i)teration' and '(t)urbulent'  and put the
> rest into an array:
> 
> # -- plot residuals 
>   import re
> filename="flutest"
> reversed_flow=re.compile('^\ re')
> turbulent_viscosity_ratio=re.compile('^\ tu')
> iteration=re.compile('^\ \ i')
> 
> begin_of_res=re.compile('>\ \ \ i')
> end_of_res=re.compile('^\ ad')

The following regular expressions have some extra backslashes 
which change their meaning:

> begin_of_writing=re.compile('^\Writing')
> end_of_writing=re.compile('^\Done')

But I don't think you need regular expressions at all. 
Also, it's better to iterate over the file just once because 
you don't need to remember the position of regions to be skipped. 
Here's a simplified demo:

def skip_region(items, start, end):
items = iter(items)
while 1:
for line in items:
if start(line):
break
yield line
else:
break
for line in items:
if end(line):
break
else:
break

def begin(line): 
return line.strip() == "Writing"

def end(line): 
return line.strip() == "Done."

# --- begin demo setup (remove to test with real data) ---
def open(filename):
from StringIO import StringIO
return StringIO("""\
iteration # to be ignored
alpha
beta
reversed # to be ignored
Writing
to
be
ignored
Done.
gamma
delta

""")
# --- end demo setup ---

if __name__ == "__main__":
filename = "fluetest"
for line in skip_region(open(filename), begin, end):
line = line.strip()
if line and not line.startswith(("reversed", "iteration")):
print line

skip_region() takes a file (or any iterable) and two functions
that test for the begin/end of the region to be skipped.
You can nest skip_region() calls if you have regions with different 
start/end conditions.

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


Re: Python 3K or Python 2.9?

2007-09-14 Thread Bjoern Schliessmann
Bruno Desthuilliers wrote:
> A method is a thin wrapper around a function, usually instanciated
> and returned by the __get__ method [1] of the function itself when
> the function is looked up as an attribute of a class or an
> instance:
> [...]

That's interesting, thank you for the explanation.

> They aren't, and you should perhaps read the manual - all this is
> documented.

Found it. :)
 
Regards,


Björn

-- 
BOFH excuse #144:

Too few computrons available.

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


Re: Python 3K or Python 2.9?

2007-09-14 Thread Bjoern Schliessmann
Terry Reedy wrote:
> No it does not.  The method wrapping is done at runtine.  The
> compiler is ignorant of the wrapping that will be done.

Agreed, after reading the docs.
 
 dis.dis(f)
>   1   0 LOAD_GLOBAL  0 (c)
>   3 LOAD_ATTR1 (meth)
>   6 CALL_FUNCTION0
>   9 RETURN_VALUE
> 
> The function gets wrapped as a bound method as part of LOAD_ATTR. 
> When the compiler sees (args), it does not know and does not
> care about the
> particular type that  will become.  It just assumes that it
> will be
> callable and emits the code to call it.  Consider

That's interesting. BTW, do you know something (apart from the dis
docs) that's worth reading if you're interested in Python byte
code?

Regards,


Björn

-- 
BOFH excuse #138:

BNC (brain not connected)

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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Antoon Pardon
On 2007-09-14, Mark Summerfield <[EMAIL PROTECTED]> wrote:
> On 14 Sep, 02:35, Jürgen Urner <[EMAIL PROTECTED]> wrote:
>> Puh, what a discussion... most common use case I can think of is
>>
>> >> d = {'a': 1, 'b': 2, 'c': 3}
>> >> for key in d:
>> >> # do something that relies on order of keys as specified in the 
>> >> constructor
>>
>> It's a bit tireing having to type
>>
>> >> for key in sorted(d.keys()):
>> >> do_somethig_with(d[key])
>>
>> instead of a trustfully
>>
>> >> for value in d.values():
>> >> do_somethig_with(value)
>>
>> As far as I can see much cleaner. No black magic needed ++ sort the
>> dict
>> to another order and rely on the sort order being stable would be a
>> really
>> a nice thing to have.
>>
>> My 2 cents,  Jürgen
>
> What I envisage is:
>
> d = ordereddict(a=1, x=20, b=35, m=4)
> # some time later
> d["e"] = 15
> # later still
> d["b"] = 70
> d.keys() # returns ['a', 'b', 'e', 'm', 'x']
> d.values() # returns [1, 70, 15, 4, 20]
>

which seems to be exactly what my avltree module mentioned earlier
provides.

>>> from avltree import Tree
>>> d=Tree(a=1, x=20, b=35, m=4)
>>> d["e"] = 15
>>> d["b"] = 70
>>> d.keys()
['a', 'b', 'e', 'm', 'x']
>>> d.values()
[1, 70, 15, 4, 20]

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


smtp debugging methods

2007-09-14 Thread Sean Nakasone
I'm having trouble with sending smtp mail.  It's hanging after the 
smtplib.SMTP() line. It doesn't works from home but not from work.  What's 
the best way to debug this?

# Here's my script
import smtplib
msg = "Subject: Hello\n\nThis is the\nbody of the message."
server = smtplib.SMTP("smtp.gmail.com",465)
   # "Connection refused" normally means there is no server listening for
   # connections on the specified IP/port-combination.
   # use netstat -an to view connections.
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
# !!! set the password
server.login("myuser", "mypass")
server.sendmail("...

# Here's the error
>>> server = smtplib.SMTP("smtp.gmail.com",465)
Traceback (most recent call last):
   File "", line 1, in ?
   File "/usr/lib/python2.4/smtplib.py", line 241, in __init__
 (code, msg) = self.connect(host, port)
   File "/usr/lib/python2.4/smtplib.py", line 304, in connect
 (code, msg) = self.getreply()
   File "/usr/lib/python2.4/smtplib.py", line 345, in getreply
 line = self.file.readline()
   File "/usr/lib/python2.4/socket.py", line 340, in readline
 data = self._sock.recv(self._rbufsize)
socket.error: (113, 'Software caused connection abort')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: smtp debugging methods

2007-09-14 Thread Jon Ribbens
On 2007-09-14, Sean Nakasone <[EMAIL PROTECTED]> wrote:
> I'm having trouble with sending smtp mail.  It's hanging after the 
> smtplib.SMTP() line. It doesn't works from home but not from work.  What's 
> the best way to debug this?
>
> # Here's the error
 server = smtplib.SMTP("smtp.gmail.com",465)

smtp.gmail.com port 465 is SSL only. Try port 587 instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: smtp debugging methods

2007-09-14 Thread Tim Williams
On 14/09/2007, Sean Nakasone <[EMAIL PROTECTED]> wrote:
> I'm having trouble with sending smtp mail.  It's hanging after the
> smtplib.SMTP() line. It doesn't works from home but not from work.  What's
> the best way to debug this?
>
> # Here's my script
> import smtplib
> msg = "Subject: Hello\n\nThis is the\nbody of the message."
> server = smtplib.SMTP("smtp.gmail.com",465)
>   # "Connection refused" normally means there is no server listening for
>   # connections on the specified IP/port-combination.
>   # use netstat -an to view connections.
> server.set_debuglevel(1)
> server.ehlo()
> server.starttls()
> server.ehlo()
> # !!! set the password
> server.login("myuser", "mypass")
> server.sendmail("...
>
> # Here's the error
> >>> server = smtplib.SMTP("smtp.gmail.com",465)
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/lib/python2.4/smtplib.py", line 241, in __init__
> (code, msg) = self.connect(host, port)
>   File "/usr/lib/python2.4/smtplib.py", line 304, in connect
> (code, msg) = self.getreply()
>   File "/usr/lib/python2.4/smtplib.py", line 345, in getreply
> line = self.file.readline()
>   File "/usr/lib/python2.4/socket.py", line 340, in readline
> data = self._sock.recv(self._rbufsize)
> socket.error: (113, 'Software caused connection abort')

There is no SMTP service on port 465 , its some other "service" or the
smtp server is in trouble,   try it with port 587 instead.

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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Mark Summerfield
On 14 Sep, 10:49, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> On 2007-09-14, Mark Summerfield <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 14 Sep, 02:35, Jürgen Urner <[EMAIL PROTECTED]> wrote:
> >> Puh, what a discussion... most common use case I can think of is
>
> >> >> d = {'a': 1, 'b': 2, 'c': 3}
> >> >> for key in d:
> >> >> # do something that relies on order of keys as specified in the 
> >> >> constructor
>
> >> It's a bit tireing having to type
>
> >> >> for key in sorted(d.keys()):
> >> >> do_somethig_with(d[key])
>
> >> instead of a trustfully
>
> >> >> for value in d.values():
> >> >> do_somethig_with(value)
>
> >> As far as I can see much cleaner. No black magic needed ++ sort the
> >> dict
> >> to another order and rely on the sort order being stable would be a
> >> really
> >> a nice thing to have.
>
> >> My 2 cents,  Jürgen
>
> > What I envisage is:
>
> > d = ordereddict(a=1, x=20, b=35, m=4)
> > # some time later
> > d["e"] = 15
> > # later still
> > d["b"] = 70
> > d.keys() # returns ['a', 'b', 'e', 'm', 'x']
> > d.values() # returns [1, 70, 15, 4, 20]
>
> which seems to be exactly what my avltree module mentioned earlier
> provides.
>
> >>> from avltree import Tree
> >>> d=Tree(a=1, x=20, b=35, m=4)
> >>> d["e"] = 15
> >>> d["b"] = 70
> >>> d.keys()
>
> ['a', 'b', 'e', 'm', 'x']>>> d.values()
>
> [1, 70, 15, 4, 20]

Antoon,

Your AVL tree looks impressive (although it has five times the lines
of my ordereddict), but it does not appear to support dict.update()'s
API (which was extended in 2.4), so you can't do: avl.update({'g':
20}, a=9, b=22).

Also, it does not provide the key(), value(), and item() methods that
the API I proposed can support (because in an ordereddict, index
positions make sense).

If there was consensus on an API and you, me, and others had different
implementations, we could always come up with some tests to compare
their relative performance, and put the fastest one(s) forward in a
PEP. (I don't care if my own code is used or not, it is the
functionality in Python's standard library that I want, whoever's code
it is.)

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

Re: recursion

2007-09-14 Thread Gigs_
sorry i think that i express wrong. having problem with english


what i mean is how python knows to add all thing at the end of recursion

 >>> def f(l):
 if l == []:
 return []
 else:
 return f(l[1:]) + l[:1]


f([1,2,3])

recursion1   f([2,3]) + [1]

recursion2   f([3]) + [2]  or [2, 1]?

recursion3   f([]) + [3] or   [3, 2, 1]


i dont get all this

 >>> def f(l):
 if l == []:
print l
 return []
 else:
 return f(l[1:]) + l[:1]

 >>> f([1,2,3])
[]
[3, 2, 1]  # how this come here? how python save  variables from each recursion?


sorry again for first post


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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Antoon Pardon
On 2007-09-14, Mark Summerfield <[EMAIL PROTECTED]> wrote:
> On 14 Sep, 10:49, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>> > # some time later
>> > d["e"] = 15
>> > # later still
>> > d["b"] = 70
>> > d.keys() # returns ['a', 'b', 'e', 'm', 'x']
>> > d.values() # returns [1, 70, 15, 4, 20]
>>
>> which seems to be exactly what my avltree module mentioned earlier
>> provides.
>>
>> >>> from avltree import Tree
>> >>> d=Tree(a=1, x=20, b=35, m=4)
>> >>> d["e"] = 15
>> >>> d["b"] = 70
>> >>> d.keys()
>>
>> ['a', 'b', 'e', 'm', 'x']>>> d.values()
>>
>> [1, 70, 15, 4, 20]
>
> Antoon,
>
> Your AVL tree looks impressive (although it has five times the lines
> of my ordereddict), but it does not appear to support dict.update()'s
> API (which was extended in 2.4), so you can't do: avl.update({'g':
> 20}, a=9, b=22).

It is true that I didn't follow up the API difference made to dict
since I wrote the module, but I think these are rather minor.
I don't think it would take a lot of work to correct these.

> Also, it does not provide the key(), value(), and item() methods that
> the API I proposed can support (because in an ordereddict, index
> positions make sense).

At the time I wrote my module I never had a need for these. Do you have
a use case or is it a consideration of completeness that makes you want
these? Maybe I can take a look in how to implement this, but at this
moment it doesn't sound that usefull to me.

On the other hand your API doesn't seem to allow for iterating over only
a part of the keys. Supposing all keys are strings, I can easily iterate
over all keys that start with an 'n' or with any arbitrary prefix.
That IMO seems more usefull.

> If there was consensus on an API and you, me, and others had different
> implementations, we could always come up with some tests to compare
> their relative performance, and put the fastest one(s) forward in a
> PEP. (I don't care if my own code is used or not, it is the
> functionality in Python's standard library that I want, whoever's code
> it is.)

Good luck on finding that consensus. If you really want this I fear you
will have to start writing that PEP before a consensus is reached and
hope to find a proposal that will be acceptable to the majority and
especially the BDFL.

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


Re: recursion

2007-09-14 Thread Marc 'BlackJack' Rintsch
On Fri, 14 Sep 2007 13:40:17 +0200, Gigs_ wrote:

> sorry i think that i express wrong. having problem with english
> 
> 
> what i mean is how python knows to add all thing at the end of recursion

Because you have written code that tells Python to do so.  ;-)

>  >>> def f(l):
>  if l == []:
>  return []
>  else:
>  return f(l[1:]) + l[:1]
> 
> 
> f([1,2,3])
> 
> recursion1   f([2,3]) + [1]
> 
> recursion2   f([3]) + [2]  or [2, 1]?
> 
> recursion3   f([]) + [3] or   [3, 2, 1]

Both alternatives in recursion 2 and 3 are wrong.  You have to simply
replace the function invocation by its result which gives:

f([1, 2, 3])
r1  f([2, 3]) + [1]
r2  f([3]) + [2] + [1]
r3  f([]) + [3] + [2] + [1]
r4  [] + [3] + [2] + [1]

And now the calls return:

r3  [3] + [2] + [1]
r2  [3, 2] + [1]
r1  [3, 2, 1]

> i dont get all this
> 
>  >>> def f(l):
>  if l == []:
>   print l
>  return []
>  else:
>  return f(l[1:]) + l[:1]
> 
>  >>> f([1,2,3])
> []
> [3, 2, 1]  # how this come here? how python save variables from each
> recursion?

There is not just one `l` but one distinct `l` in each call.

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


Re: Python 3K or Python 2.9?

2007-09-14 Thread Duncan Booth
Piet van Oostrum <[EMAIL PROTECTED]> wrote:

>> Ben Finney <[EMAIL PROTECTED]> (BF) wrote:
> 
>>BF> The latter two statements are equivalent. The
>>'instance.method(args)' BF> syntax is just sugar for
>>'Class.method(instance, args)'. 
> 
> It is more than just syntactic sugar because the Class is derived from
> the instance at runtime. 

Other differences that mean it isn't just sugar:

you can save the bound method created by 'instance.method' but not with the 
expanded version.

The equivalence depends on the type of 'method', other expansions are 
possible: e.g. Class.method(Class, args) or Class.method(args) or invent 
your own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Install Mac OS X - Idle doesn't show up

2007-09-14 Thread Dominique
Hello,

Sorry bothering you with such a trivial problem.

I installed python on a new mac at office.
It seems everything is fine: in the console, I access to python.
But I just can't start Idle. It seems to open but closes immediately (it appears
in the dock and closes immediately).
It is also impossible to open any .py file.

I am sure some of you have a good idea of what to do (path,...).

Thanks in advance
Dominique

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


Re: recursion

2007-09-14 Thread Steve Holden
Gigs_ wrote:
> sorry i think that i express wrong. having problem with english
> 
> 
> what i mean is how python knows to add all thing at the end of recursion
> 
>  >>> def f(l):
>  if l == []:
>  return []
>  else:
>  return f(l[1:]) + l[:1]
> 
> 
> f([1,2,3])
> 
> recursion1   f([2,3]) + [1]
> 
> recursion2   f([3]) + [2]  or [2, 1]?
> 
> recursion3   f([]) + [3] or   [3, 2, 1]
> 
> 
> i dont get all this
> 
>  >>> def f(l):
>  if l == []:
>   print l
>  return []
>  else:
>  return f(l[1:]) + l[:1]
> 
>  >>> f([1,2,3])
> []
> [3, 2, 1]  # how this come here? how python save  variables from each 
> recursion?
> 
> 
> sorry again for first post
> 
I think the thing you are missing is that the recursive call f(l[1:]) in 
the return statement causes the current call to be suspended until the 
recursive call is complete. The new call has its own value for l, which 
is the caller's l[1:]. Each new call creates a completely new namespace.

A less complicated function might make it a little more obvious.

  def factorial(n):
 print "n =", n
 if n=0:
 return 1
 else:
 return n * factorial(n-1)

Try running that with a few different arguments to show you how the 
recursion works.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline

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


Re: recursion

2007-09-14 Thread John Machin
On Sep 14, 10:04 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Fri, 14 Sep 2007 13:40:17 +0200, Gigs_ wrote:
> > sorry i think that i express wrong. having problem with english
>
> > what i mean is how python knows to add all thing at the end of recursion
>
> Because you have written code that tells Python to do so.  ;-)
>
> >  >>> def f(l):
> >  if l == []:
> >  return []
> >  else:
> >  return f(l[1:]) + l[:1]
>
> > f([1,2,3])
>
> > recursion1   f([2,3]) + [1]
>
> > recursion2   f([3]) + [2]  or [2, 1]?
>
> > recursion3   f([]) + [3] or   [3, 2, 1]
>
> Both alternatives in recursion 2 and 3 are wrong.  You have to simply
> replace the function invocation by its result which gives:
>
> f([1, 2, 3])
> r1  f([2, 3]) + [1]
> r2  f([3]) + [2] + [1]
> r3  f([]) + [3] + [2] + [1]
> r4  [] + [3] + [2] + [1]
>
> And now the calls return:
>
> r3  [3] + [2] + [1]
> r2  [3, 2] + [1]
> r1  [3, 2, 1]
>
> > i dont get all this
>
> >  >>> def f(l):
> >  if l == []:
> >print l
> >  return []
> >  else:
> >  return f(l[1:]) + l[:1]
>
> >  >>> f([1,2,3])
> > []
> > [3, 2, 1]  # how this come here? how python save variables from each
> > recursion?
>
> There is not just one `l` but one distinct `l` in each call.
>

I reckon that what the OP wants is a simple explanation of how
function calls use a stack mechanism for arguments and local
variables, and how this allows recursive calls, unlike the good ol'
FORTRAN IV of blessed memory. Perhaps someone could oblige him?

I'd try but it's time for my beauty sleep :-)

Good night all
John

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


Re: Install Mac OS X - Idle doesn't show up

2007-09-14 Thread Dominique
Dominique  gmail.com> writes:

> 
> 
One precision: When I go in the console and type idle, it works: idle appears.
But I would like to be able to launch idle from the dock
Dominique




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


Re: "once" assigment in Python

2007-09-14 Thread Lorenzo Di Gregorio
Thank you very much for your suggestions!
I'll try in the next days to elaborate a bit on the last two ones.

By the way, the "once" assignment is not that evil if you use it for
hardware modeling.
Most hardware models look like:

wire1 = function()
instance component(input=wire1,output=wire2)
result = function(wire2)

When employing Python it's pretty straightforward to translate the
instance to an object.

instance = Component(input=wire1,output=wire2)

Then you don't use "instance" *almost* anymore: it's an object which
gets registered with the simulator kernel and gets called by reference
and event-driven only by the simulator kernel.  We might reuse the
name for calling some administrative methods related to the instance
(e.g. for reporting) but that's a pretty safe thing to do.  Of course
all this can be done during initialization, but there are some good
reasons (see Verilog vs VHDL) why it's handy do be able to do it
*anywhere*.  The annoying problem was that every time the program flow
goes over the assignment, the object gets recreated.

Indeed Python itself is not a hardware modeling language, but I built
some infrastructure to fill what I was missing and for quickly
building up a functional prototype and testing some ideas Python is
really excellent.

Best Regards,
Lorenzo

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


Re: extract text from log file using re

2007-09-14 Thread Paul McGuire
On Sep 13, 4:09 pm, Fabian Braennstroem <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I would like to delete a region on a log file which has this
> kind of structure:
>

How about just searching for what you want.  Here are two approaches,
one using pyparsing, one using the batteries-included re module.

-- Paul


# -*- coding: iso-8859-15 -*-
data = """\
   498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04
3.8560e-03 4.8384e-02 11:40:01  499
   499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04
3.8560e-03 4.8384e-02 11:40:01  499
reversed flow in 1 faces on pressure-outlet 35.

Writing
"/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/
fluent-050­0.cas"...
 5429199 mixed cells, zone 29, binary.
11187656 mixed interior faces, zone 30, binary.
   20004 triangular wall faces, zone 31, binary.
1104 mixed velocity-inlet faces, zone 32, binary.
  133638 triangular wall faces, zone 33, binary.
   14529 triangular wall faces, zone 34, binary.
1350 mixed pressure-outlet faces, zone 35, binary.
   11714 mixed wall faces, zone 36, binary.
 1232141 nodes, binary.
 1232141 node flags, binary.
Done.

Writing
"/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/
fluent-050­0.dat"...
Done.


   500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04
3.8545e-03 1.3315e-01 11:14:10  500


 reversed flow in 2 faces on pressure-outlet 35.
   501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04
3.8560e-03 4.8384e-02 11:40:01  499
"""

print "search using pyparsing"
from pyparsing import *

integer = Word(nums).setParseAction(lambda t:int(t[0]))
scireal = Regex(r"\d*\.\d*e\-\d\d").setParseAction(lambda
t:float(t[0]))
time = Regex(r"\d\d:\d\d:\d\d")

logline = (integer("testNum") +
   And([scireal]*7)("data") +
   time("testTime") +
   integer("result"))

for tRes in logline.searchString(data):
print "Test#:",tRes.testNum
print "Data:", tRes.data
print "Time:", tRes.testTime
print "Output:", tRes.result
print

print
print "search using re's"
import re
integer = r"\d*"
scireal = r"\d*\.\d*e\-\d\d"
time = r"\d\d:\d\d:\d\d"
ws = r"\s*"

namedField = lambda reStr,n: "(?P<%s>%s)" % (n,reStr)
logline = re.compile(
namedField(integer,"testNum") + ws +
namedField( (scireal+ws)*7,"data" ) +
namedField(time,"testTime") + ws +
namedField(integer,"result") )
for m in logline.finditer(data):
print "Test#:",int(m.group("testNum"))
print "Data:", map(float,m.group("data").split())
print "Time:", m.group("testTime")
print "Output:", int(m.group("result"))
print

Prints:

search using pyparsing
Test#: 498
Data: [0.0010085, 0.000246079997,
9.85890001e-005, 0.00014908, 0.000839560005,
0.0038561, 0.0483840003]
Time: 11:40:01
Output: 499

Test#: 499
Data: [0.0010085, 0.000246079997,
9.85890001e-005, 0.00014908, 0.000839560005,
0.0038561, 0.0483840003]
Time: 11:40:01
Output: 499

Test#: 500
Data: [0.0010049, 0.00024632, 9.83949996e-005,
0.000148650001, 0.00083913, 0.0038544,
0.13314]
Time: 11:14:10
Output: 500

Test#: 501
Data: [0.0010085, 0.000246079997,
9.85890001e-005, 0.00014908, 0.000839560005,
0.0038561, 0.0483840003]
Time: 11:40:01
Output: 499


search using re's
Test#: 498
Data: [0.0010085, 0.000246079997,
9.85890001e-005, 0.00014908, 0.000839560005,
0.0038561, 0.0483840003]
Time: 11:40:01
Output: 499

Test#: 499
Data: [0.0010085, 0.000246079997,
9.85890001e-005, 0.00014908, 0.000839560005,
0.0038561, 0.0483840003]
Time: 11:40:01
Output: 499

Test#: 500
Data: [0.0010049, 0.00024632, 9.83949996e-005,
0.000148650001, 0.00083913, 0.0038544,
0.13314]
Time: 11:14:10
Output: 500

Test#: 501
Data: [0.0010085, 0.000246079997,
9.85890001e-005, 0.00014908, 0.000839560005,
0.0038561, 0.0483840003]
Time: 11:40:01
Output: 499


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

Re: How to Start

2007-09-14 Thread Shawn Milochik
On 9/14/07, James Stroud <[EMAIL PROTECTED]> wrote:
>
> Here's your recipe:
>
>1. begin coding until you hit a wall
>2. read official tutorial until you figure out a solution
>3. experiment in interactive interpreter
>4. goto 1.
>
> I know this sounds obvious, but its the best way to jumpstart.
>
> James
> --

What a beautiful way of putting it! That's what I do all the time,
although sometimes my bookshelf or Google is a stand-in for #2. I try
not to post to the list before I have working code.

You know, if you could make that process into a haiku, you could just
make that your sig and answer nearly every question that hits this
list. ^_^

I wonder whether lists like this hurt more people than they help,
because it's too easy to ask for help too soon. Those of you who
consistently  give the best advice didn't learn by asking for help
every step along the way, did you? Is it really teaching a man to fish
if you bait his line and tell him where to cast?

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


Re: Install Mac OS X - Idle doesn't show up

2007-09-14 Thread Kevin Walzer
Dominique wrote:
> Hello,
> 
> Sorry bothering you with such a trivial problem.
> 
> I installed python on a new mac at office.
> It seems everything is fine: in the console, I access to python.
> But I just can't start Idle. It seems to open but closes immediately (it 
> appears
> in the dock and closes immediately).
> It is also impossible to open any .py file.
> 
> I am sure some of you have a good idea of what to do (path,...).
> 
> Thanks in advance
> Dominique
> 
How did you install/build Python? On the Mac, you really aren't supposed 
to start it from the terminal unless you are running it under X11 or are 
using a non-framework build. If you built it the standard Mac way, or if 
you use the binary installer from python.org, Idle is installed in 
/Applications/MacPython 2.5. Look there, and you should be able to drag 
the Idle icon to the dock.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] Just bought Python in a Nutshell

2007-09-14 Thread Shawn Milochik
My best advice:

Skim it -- just flip the pages, glancing at each one without really
reading it -- maybe just read the bold type. You'll find that very
rewarding when you run into a problem in your coding and remember that
you saw *something* which could be related. You will probably notice
some built-in functions that you will need and possibly would have
re-invented if you didn't know they were there.

I don't really find it to be a "reading" book -- it's more of a
reference book. Flip through it, then keep it within reach of your
keyboard.

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


Re: [Tutor] list iteration question for writing to a file on disk

2007-09-14 Thread Shawn Milochik
When you use "print," it automatically adds a newline (\n).

You can avoid this by following the print line with a comma:

print j,

Or rstrip() the line before printing. Either way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Mark Summerfield
On 14 Sep, 12:46, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> On 2007-09-14, Mark Summerfield <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 14 Sep, 10:49, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> >> > # some time later
> >> > d["e"] = 15
> >> > # later still
> >> > d["b"] = 70
> >> > d.keys() # returns ['a', 'b', 'e', 'm', 'x']
> >> > d.values() # returns [1, 70, 15, 4, 20]
>
> >> which seems to be exactly what my avltree module mentioned earlier
> >> provides.
>
> >> >>> from avltree import Tree
> >> >>> d=Tree(a=1, x=20, b=35, m=4)
> >> >>> d["e"] = 15
> >> >>> d["b"] = 70
> >> >>> d.keys()
>
> >> ['a', 'b', 'e', 'm', 'x']>>> d.values()
>
> >> [1, 70, 15, 4, 20]
>
> > Antoon,
>
> > Your AVL tree looks impressive (although it has five times the lines
> > of my ordereddict), but it does not appear to support dict.update()'s
> > API (which was extended in 2.4), so you can't do: avl.update({'g':
> > 20}, a=9, b=22).
>
> It is true that I didn't follow up the API difference made to dict
> since I wrote the module, but I think these are rather minor.
> I don't think it would take a lot of work to correct these.

I'm sure you're right.

> > Also, it does not provide the key(), value(), and item() methods that
> > the API I proposed can support (because in an ordereddict, index
> > positions make sense).
>
> At the time I wrote my module I never had a need for these. Do you have
> a use case or is it a consideration of completeness that makes you want
> these? Maybe I can take a look in how to implement this, but at this
> moment it doesn't sound that usefull to me.

I put them in for completeness, although in some contexts I have found
the ability to ask for the n-th item to be v. useful.

> On the other hand your API doesn't seem to allow for iterating over only
> a part of the keys. Supposing all keys are strings, I can easily iterate
> over all keys that start with an 'n' or with any arbitrary prefix.
> That IMO seems more usefull.

That is an appealing feature---but I don't want to make any assumption
about keys (they could be ints, id()s, strs, or anything that is
acceptable to a dict.

There's nothing to stop you creating a PEP for your AVL tree---I'd
certainly be glad for one to be in the collections module. I'm not
advocating "only one" ordered data structure, but rather one
particular one---and I certainly hope the collections module will have
several eventually, and that other people will propose PEPs for other
data structures, such as AVL trees, B*Trees, skiplists, etc., since
all have something to offer.

> > If there was consensus on an API and you, me, and others had different
> > implementations, we could always come up with some tests to compare
> > their relative performance, and put the fastest one(s) forward in a
> > PEP. (I don't care if my own code is used or not, it is the
> > functionality in Python's standard library that I want, whoever's code
> > it is.)
>
> Good luck on finding that consensus. If you really want this I fear you
> will have to start writing that PEP before a consensus is reached and
> hope to find a proposal that will be acceptable to the majority and
> especially the BDFL.

I don't expect my API to satisfy everyone, but by making it as close
to what exists already, i.e., a dict, yet with keys that "happen" to
be ordered (and offering a few extra methods to help users exploit
that if they want), I am hoping this will make it more likely to be
acceptable.


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


Re: recursion

2007-09-14 Thread Gigs_
Steve Holden wrote:
> Gigs_ wrote:
>> sorry i think that i express wrong. having problem with english
>>
>>
>> what i mean is how python knows to add all thing at the end of recursion
>>
>>  >>> def f(l):
>>  if l == []:
>>  return []
>>  else:
>>  return f(l[1:]) + l[:1]
>>
>>
>> f([1,2,3])
>>
>> recursion1   f([2,3]) + [1]
>>
>> recursion2   f([3]) + [2]  or [2, 1]?
>>
>> recursion3   f([]) + [3] or   [3, 2, 1]
>>
>>
>> i dont get all this
>>
>>  >>> def f(l):
>>  if l == []:
>> print l
>>  return []
>>  else:
>>  return f(l[1:]) + l[:1]
>>
>>  >>> f([1,2,3])
>> []
>> [3, 2, 1]  # how this come here? how python save  variables from each 
>> recursion?
>>
>>
>> sorry again for first post
>>
> I think the thing you are missing is that the recursive call f(l[1:]) in 
> the return statement causes the current call to be suspended until the 
> recursive call is complete. The new call has its own value for l, which 
> is the caller's l[1:]. Each new call creates a completely new namespace.
> 
> A less complicated function might make it a little more obvious.
> 
>  def factorial(n):
> print "n =", n
> if n=0:
> return 1
> else:
> return n * factorial(n-1)
> 
> Try running that with a few different arguments to show you how the 
> recursion works.
> 
> regards
>  Steve
 >>> def factorial(n):
print "n =", n
if n==0:
return 1
else:
return n * factorial(n-1)

 >>> factorial(3)
n = 3
n = 2
n = 1
n = 0
6


now i understand. but one question at the end this function return 1. how 
python 
knows that it needs to multiply 1 with all recursive returns. (why python didnt 
sum recursive return with 1?)


that will be all, thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


where is help file?

2007-09-14 Thread PaulS
new to Fedora7, typed python in interactive interpreter, then help().  Then 
modules to get a list of modules.  Then module name to get info on a module 
but no help file.  What is the help file name?  Is there an environmental 
variable I have to set?  Thanks,
Paul 


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


Re: recursion

2007-09-14 Thread J. Clifford Dyer

On Fri, Sep 14, 2007 at 01:40:17PM +0200, Gigs_ wrote regarding Re: recursion:
> 
> what i mean is how python knows to add all thing at the end of recursion
> 
>  >>> def f(l):
>  if l == []:
>  return []
>  else:
>  return f(l[1:]) + l[:1]
> 

The following script does exactly the same thing, except it creates print 
statements to help you figure out what's going on, and it binds f(L[1:]) to 
a variable so you can use it again.

def f(L):  # l capitalized to accentuate difference between l and 1.
print "L =", L
print "L[1:] =", L[1:]
print "L[:1] =", L[:1]
if L == []:
print "Return: ", []
return []
else:
next = f(L[1:])
print "Return: ", next, "+", L[:1], "=", next + L[:1]
return next + L[:1]

if __name__=='__main__':
print f(['A', 'B', 'C', 'D'])

Try it out.  See what happens.

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


Re: where is help file?

2007-09-14 Thread Carsten Haese
On Fri, 2007-09-14 at 10:00 -0400, PaulS wrote:
> new to Fedora7, typed python in interactive interpreter, then help().  Then 
> modules to get a list of modules.  Then module name to get info on a module 
> but no help file.  What is the help file name?  Is there an environmental 
> variable I have to set?

There is no help file, and no environment variable. The help text is
stored directly inside each module and function that supplies a help
text. Observe:

>>> def f(x):
...   "Calculate the square of x."
...   return x**x
... 
>>> help(f)
Help on function f in module __main__:

f(x)
Calculate the square of x.
(END) 

Providing such a help text is optional, but all standard library modules
do provide help as far as I know. Consequently, the fact that you have a
module that doesn't provide a help text seems to indicate that it's not
a standard library module. What's the name of the module you're trying
to get help on?

Hope this helps (no pun intended),

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: recursion

2007-09-14 Thread Neil Cerutti
On 2007-09-14, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 14, 10:04 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Fri, 14 Sep 2007 13:40:17 +0200, Gigs_ wrote:
>> > sorry i think that i express wrong. having problem with english
>>
>> > what i mean is how python knows to add all thing at the end of recursion
>>
>> Because you have written code that tells Python to do so.  ;-)
>>
>> >  >>> def f(l):
>> >  if l == []:
>> >  return []
>> >  else:
>> >  return f(l[1:]) + l[:1]
>>
>> > f([1,2,3])
>>
>> > recursion1   f([2,3]) + [1]
>>
>> > recursion2   f([3]) + [2]  or [2, 1]?
>>
>> > recursion3   f([]) + [3] or   [3, 2, 1]
>>
>> Both alternatives in recursion 2 and 3 are wrong.  You have to
>> simply replace the function invocation by its result which
>> gives:
>>
>> f([1, 2, 3])
>> r1  f([2, 3]) + [1]
>> r2  f([3]) + [2] + [1]
>> r3  f([]) + [3] + [2] + [1]
>> r4  [] + [3] + [2] + [1]
>>
>> And now the calls return:
>>
>> r3  [3] + [2] + [1]
>> r2  [3, 2] + [1]
>> r1  [3, 2, 1]
>>
>> > i dont get all this
>>
>> >  >>> def f(l):
>> >  if l == []:
>> >print l
>> >  return []
>> >  else:
>> >  return f(l[1:]) + l[:1]
>>
>> >  >>> f([1,2,3])
>> > []
>> > [3, 2, 1]  # how this come here? how python save variables from each
>> > recursion?
>>
>> There is not just one `l` but one distinct `l` in each call.
>>
>
> I reckon that what the OP wants is a simple explanation of how
> function calls use a stack mechanism for arguments and local
> variables, and how this allows recursive calls, unlike the good ol'
> FORTRAN IV of blessed memory. Perhaps someone could oblige him?
>
> I'd try but it's time for my beauty sleep :-)
>
> Good night all

I may as well stick my neck out again, since I'm already
beautiful. ;)

Another way of understanding recursion is to break it up into
seperate functions, so the spectre of a function calling itself
doesn't appear.

def f(l):
  if l == []:
return []
  else:
return f(l[1:]) + l[:1]

The function above reverses a list of arbitrary length. To help
understand how it works, I'll write several discreet functions
that sort lists of fixed lengths.

I start with a simple case (though not the simplest case--that
only comes with experience), reversing a two-element list:

def f2(l): # reverse a two-element list
  return [l[1], l[0]]

Next build up to the next level, writing a function that can
reverse a three-element list. The key is to be as lazy as
possible. You must figure out a way of taking advantage of the
function that reverses a two-element list. The obvious solution
is to use f2 to reverse the last two elements in our list, and
append the first element in the list to that result:

def f3(l): # reverse a three-element list
  return f2(l[1:]) + l[:1]

And so on:

def f4(l):
  return f3(l[1:]) + l[:1]

def f5(l):
  return f4(l[1:]) + l[:1]

def f6(l):
  return f5(l[1:]) + l[:1]

A definite pattern had emerged, and it should be apparent now how
to combine all those functions into one:

def f_(l):
  if len(l) == 2:
return [l[1], l[0]]
  else:
return f_(l[1:]) + l[:1]

But the function above breaks for lists with less than two items.

>>> f_([1])
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in f2
IndexError: list index out of range

We can handle that. The reverse of a zero or one-element list is
just itself.

def f_(l):
  if len(l) < 2:
return l
  elif len(l) == 2:
return [l[1], l[0]]
  else:
return f_(l[1:]) + l[:1]

And we've arrived at an OK recursive function that can handle
arbitrary length lists. It's not as simple as it could be,
however. A little intuitive leap, perhaps, will allow you to note
that the case of a two-element list can actually be handled
without a special case:

def f(l):
  if len(l) < 2:
return l
  else:
return f(l[1:]) + l[:1]

Final note: for reasons of tradition, base cases are almost
always set up as it was in the original function, checking for a
zero-length list, and returning a new empty list, the truly
simplest base case. Another intuitive leap is possibly required
to note that a one-element list is not a special case after all:
it's a reverse of a zero-element list with that one element
appended.

def f(l):
  if len(l) == 0:
return []
  else:
return f(l[1:]) + l[:1]

Clear as mud?

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


Re: Install Mac OS X - Idle doesn't show up

2007-09-14 Thread Dominique
Kevin Walzer  codebykevin.com> writes:

> 
> > 
> How did you install/build Python? On the Mac, you really aren't supposed 
> to start it from the terminal unless you are running it under X11 or are 
> using a non-framework build. If you built it the standard Mac way, or if 
> you use the binary installer from python.org, Idle is installed in 
> /Applications/MacPython 2.5. Look there, and you should be able to drag 
> the Idle icon to the dock.
> 

Hum Hum Hum...
That's what I did. It did not work. Now yes. ???!
I should have dreamt. I don't understand

Thank you Kevin for your help
Dominique




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


newbee: Simple Backend Python Script Question

2007-09-14 Thread joe shoemaker
I need to create python script that is threaded. So the main program will
run in infinite loop and just retrieving messages and putting them in a
queue. (Main thread)

I need child threads from a pool to process the queue. When there is no
stuff in the queue, they go to the pool and become available but they don't
terminate. This has to be done continuously.

Main program need to keep putting stuff in the queue, when there are no
messages, then it sleeps for short time and check back to see any messages.

To do this, I guess you don't write joinAll(), so that the main threads just
don't wait for the child but goes to work.

am I right?

Also, child threads (a function that is threaded) will make connecitons to
the database. I am planning to use threadpool, so that threads reuse the
connections. So do you close the database connection at the end of the
function? If not then the connection will be opened forever?


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

subclass of integers

2007-09-14 Thread Mark Morss
I would like to construct a class that includes both the integers and
None.  I desire that if x and y are elements of this class, and both
are integers, then arithmetic operations between them, such as x+y,
return the same result as integer addition.  However if either x or y
is None, these operations return None.

It's simple enough to construct a subclass of integers that behave in
this way:

class Nint(int):
def __add__(self,other):
if (other != None):
return self+other
else:
return None
def __radd__(self,other):
if (other != None):
return other+self
else:
return None
#...and so forth

However I have not been able to figure out how to make it so that
None, as well as an integer, could be an element of my class.  My
preliminary impression is that I have to override int.__new__; but I
am uncertain how to do that and have been unable to find anything on
the web explaining that.  Indeed I haven't been able to find much
about __new__ at all.  Overriding this method of built-in classes
seems to be quite unusual.

I would very much appreciate anyone's help.

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


Re: recursion

2007-09-14 Thread Marc 'BlackJack' Rintsch
On Fri, 14 Sep 2007 15:58:39 +0200, Gigs_ wrote:

>  >>> def factorial(n):
> print "n =", n
> if n==0:
> return 1
> else:
> return n * factorial(n-1)
> 
>  >>> factorial(3)
> n = 3
> n = 2
> n = 1
> n = 0
> 6
> 
> 
> now i understand. but one question at the end this function return 1. how 
> python 
> knows that it needs to multiply 1 with all recursive returns. (why python 
> didnt 
> sum recursive return with 1?)

Because there is a ``*`` and not a ``+`` in the last line of the function.

Let's play this through (I abbreviate the function name to just `f()`):

Execution of f(3) leads to the second return:

r1 f(3):  return 3 * f(2)

This multiplication can't take place until ``f(2)`` is calculated so the
current function call is "suspended" and evaluated later, when the result
of ``f(2)`` is known.  The call in that line is replaces with the result
then.  Calling ``f(2)`` leads to:

r2 f(2):  return 2 * f(1)

The same again, another call to `f()` with 1 as argument:

r3 f(1):  return 1 * f(0)

Now the last call takes the other ``if`` branch:

r4 f(0):  return 1

The 1 is returned to the previus call:

r3 f(1):  return 1 * 1

This can be evaluated now and is returned to its caller:

r2 f(2):  return 2 * 1

Again this is evaluated and returned to its caller:

r1 f(3):  return 3 * 2

And here we have the final result that is returned from the first call to
`f()`.

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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Antoon Pardon
On 2007-09-14, Mark Summerfield <[EMAIL PROTECTED]> wrote:
>> > Also, it does not provide the key(), value(), and item() methods that
>> > the API I proposed can support (because in an ordereddict, index
>> > positions make sense).
>>
>> At the time I wrote my module I never had a need for these. Do you have
>> a use case or is it a consideration of completeness that makes you want
>> these? Maybe I can take a look in how to implement this, but at this
>> moment it doesn't sound that usefull to me.
>
> I put them in for completeness, although in some contexts I have found
> the ability to ask for the n-th item to be v. useful.

If you don't have a use case, I advise you to drop them. As far as I
understand people's sentiments, including a feature without a use case
illustrating its usefullness will decrease your chances.

>> On the other hand your API doesn't seem to allow for iterating over only
>> a part of the keys. Supposing all keys are strings, I can easily iterate
>> over all keys that start with an 'n' or with any arbitrary prefix.
>> That IMO seems more usefull.
>
> That is an appealing feature---but I don't want to make any assumption
> about keys (they could be ints, id()s, strs, or anything that is
> acceptable to a dict.

The feature doesn't depend on any assumption. if your keys are integers
you can iterate over all keys between 121 and 8264. Iterating over all
keys that start with an 'n' just depends on the fact that all such
strings lie between the strings 'n' and 'o'.

However not all keys acceptable to a dict, will be acceptable to
a SortedDict. Some types are hashable but not completly comparable.
Those objects will not be usable as a key in a SortedDict although
they can be used as a key in an normal dict.

> There's nothing to stop you creating a PEP for your AVL tree---I'd
> certainly be glad for one to be in the collections module. I'm not
> advocating "only one" ordered data structure, but rather one
> particular one---and I certainly hope the collections module will have
> several eventually, and that other people will propose PEPs for other
> data structures, such as AVL trees, B*Trees, skiplists, etc., since
> all have something to offer.

I'm not interrested in writing a PEP. My impression from asking around
is that is too much work for too little chance to get it accepted.
That is more a personal evaluation of how I value my time and how much I
would prefer it to have my module included than about the PEP process
in itself.

If someone would like to use my avl module as a starting point for a PEP,
I may consider allowing that, but writing the PEP myself is going to
take too much time from other projects.

>> > If there was consensus on an API and you, me, and others had different
>> > implementations, we could always come up with some tests to compare
>> > their relative performance, and put the fastest one(s) forward in a
>> > PEP. (I don't care if my own code is used or not, it is the
>> > functionality in Python's standard library that I want, whoever's code
>> > it is.)
>>
>> Good luck on finding that consensus. If you really want this I fear you
>> will have to start writing that PEP before a consensus is reached and
>> hope to find a proposal that will be acceptable to the majority and
>> especially the BDFL.
>
> I don't expect my API to satisfy everyone, but by making it as close
> to what exists already, i.e., a dict, yet with keys that "happen" to
> be ordered (and offering a few extra methods to help users exploit
> that if they want), I am hoping this will make it more likely to be
> acceptable.

I wish you all the luck you can get. Maybe if you succeed I'll change
my mind about writing a PEP myself.

However I think your chances will increase if you write your module
and have it available in the cheese shop. If people start using your
module regularly, your chances of it being included in the standard
library will increase greatly.

-- 
Antoon Pardon

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


RE: How to Start

2007-09-14 Thread Sells, Fred
I like eclipse+pydev; although I did pay my dues learning the basics of
eclipse. F9 saves file and runs it.

If you're an emacs dude, emacs + python mode is pretty good.  ctrl-c
ctrl-c runs the active buffer.  Of course if you don't already know
emacs, avoid it like the plague.

> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED]
> Behalf Of Michael R. Copeland
> Sent: Thursday, September 13, 2007 6:00 PM
> To: python-list@python.org
> Subject: How to Start
> 
> 
>I've decided that Python is a language/environment I'd 
> like to learn 
> (I've been a professional programmer for 45+ years), but I 
> really don't 
> know where and how to start!  I have a number of books - and 
> am buying 
> some more - but because of the bewildering number of after-market 
> packages, environments, and add-ons, I am really quite 
> perplexed about 
> starting.  8<{{
>Yes, I could fire up the interactive mode and play with some 
> statements...but I consider that sort of thing for 
> programming neophytes 
> or experimenting with specific issues.  First, I want to develop a 
> simple Windows application, and because of the plethora of 
> "stuff" the 
> Python world offers, I don't know where to begin.  
>For example, what basic, easy-to-use interface might I 
> start with to 
> build a simple text file parsing and analysis program?  That is, I'd 
> like to start with a simple Windows shell that prompts for a 
> file name, 
> processes it, and then displays some result.
>I am certainly impressed with the apparent experience and 
> openness of 
> the regular players here, but the discussions here (and in 
> c.l.p.announce) truly presume knowledge and experience with Python I 
> don't yet have.  Yes, for even a very experienced programmer, 
> entering 
> the Python world is very daunting - but I want to get started.
>Please advise.  TIA
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursion

2007-09-14 Thread Steve Holden
Gigs_ wrote:
> Steve Holden wrote:
[...]
>>
>> regards
>>  Steve
>  >>> def factorial(n):
> print "n =", n
> if n==0:
> return 1
> else:
> return n * factorial(n-1)
> 
>  >>> factorial(3)
> n = 3
> n = 2
> n = 1
> n = 0
> 6
> 
> 
> now i understand. but one question at the end this function return 1. how 
> python 
> knows that it needs to multiply 1 with all recursive returns. (why python 
> didnt 
> sum recursive return with 1?)
> 
> 
> that will be all, thanks in advance

Aah, that's the magic of recursion (not that it's really magic at all).

When you call factorial(3), the function sees the value of n as 3. So 
the if condition is false, so it must execute the return statement.

In order to do that it has to multiply n by the value of factorial n-1. 
So it makes a call to a *new copy* of factorial, and this one has the 
value 2 for n. The if statement again needs to execute the return 
statement, and before it can do that it needs the value of factorial 
n-1, so it makes a call to a *new copy* of factorial, and this one has 
the value 1 for n. The if statement again needs to execute the return 
statement, and before it can do that it needs the value of factorial 
n-1, so it makes a call to a *new copy* of factorial, and this one has 
the value 0 for n. [Are you detecting a pattern here?].

Finally *this* copy of factorial can immediately return the value of 1 
to its caller, which then multiplies that by 1 and returns it ti *its 
caller, which multiplies it by 2 and returns that to *its* caller, when 
multiplies it by 3 and returns the result, 6.

In other words, the computer builds a "stack" of partially-completed 
functions, and unwinds it when the innermost (topmost, whatever) finally 
sees that it can return a result without creating another stacked call 
to factorial.

Hope this straightens it out for you, it's a bit of a head-twister when 
you first come across it.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline

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


Re: subclass of integers

2007-09-14 Thread Mark Morss
On Sep 14, 10:30 am, Mark Morss <[EMAIL PROTECTED]> wrote:
> I would like to construct a class that includes both the integers and
> None.  I desire that if x and y are elements of this class, and both
> are integers, then arithmetic operations between them, such as x+y,
> return the same result as integer addition.  However if either x or y
> is None, these operations return None.
>
> It's simple enough to construct a subclass of integers that behave in
> this way:
>
> class Nint(int):
> def __add__(self,other):
> if (other != None):
> return self+other
> else:
> return None
> def __radd__(self,other):
> if (other != None):
> return other+self
> else:
> return None
> #...and so forth
>
> However I have not been able to figure out how to make it so that
> None, as well as an integer, could be an element of my class.  My
> preliminary impression is that I have to override int.__new__; but I
> am uncertain how to do that and have been unable to find anything on
> the web explaining that.  Indeed I haven't been able to find much
> about __new__ at all.  Overriding this method of built-in classes
> seems to be quite unusual.
>
> I would very much appreciate anyone's help.

I meant of course that arithmetic operations between integer elements
would return the same result as the corresponding integer operations,
not necessarily addition.

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


Re: subclass of integers

2007-09-14 Thread Zentrader
I would do something along the lines of the following, although it
only tests for integers and not floats, so would return 'None' for a
float.

class Nint(int):
def __add__(self, x, y):
if isinstance(x, int) and isinstance(y, int):
return x+y
return None

if __name__=='__main__':
N=Nint()
print N.__add__( 1, 2 )
print N.__add__( 1, None )

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


Re: subclass of integers

2007-09-14 Thread Zentrader
This would accept ints, floats, and decimal types.

import decimal

class Nint(int):
def __add__(self, x, y):
try:
return x+y
except:
return None

if __name__=='__main__':
N=Nint()
print N.__add__( 1, 2 )
print N.__add__( 1, None )
print N.__add__(decimal.Decimal("2"), decimal.Decimal("3"))
print N.__add__(decimal.Decimal("2"), 3)

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


Re: automatic parallelization

2007-09-14 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Mikhail Teterin  <[EMAIL PROTECTED]> wrote:
.
.
.
>> I'm fond of Linda > http://www.unixreview.com/documents/s=10125/ur0704l/ >, Parallel 
>> Python http://www.parallelpython.com/ > only one of several
>> initiatives which aspire to exploit multicores, and so on.
>
>Linda URL does not open... I'll look into Parallel Python, but it is
.
.
.
It comes and goes.  It seems to have been OK the last several hours.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbee: Simple Backend Python Script Question

2007-09-14 Thread Steve Holden
joe shoemaker wrote:
> I need to create python script that is threaded. So the main program 
> will run in infinite loop and just retrieving messages and putting them 
> in a queue. (Main thread)
> 
> I need child threads from a pool to process the queue. When there is no 
> stuff in the queue, they go to the pool and become available but they 
> don't terminate. This has to be done continuously.
> 
> Main program need to keep putting stuff in the queue, when there are no 
> messages, then it sleeps for short time and check back to see any messages.
> 
> To do this, I guess you don't write joinAll(), so that the main threads 
> just don't wait for the child but goes to work.
> 
> am I right?
> 
Pretty much. The way I usually do this is to start a number of threads 
reading work items of some sort from a Queue.Queue. The thread will 
block automatically if there's nothing on the queue, resuming when 
something appears (and if I want orderly termination I use None as a 
dummy work unit, and the threads terminate when they receive a None, but 
any sentinel value would do).

> Also, child threads (a function that is threaded) will make connecitons 
> to the database. I am planning to use threadpool, so that threads reuse 
> the connections. So do you close the database connection at the end of 
> the function? If not then the connection will be opened forever?
> 
You don't want a thread pool, you want a connection pool, but there's 
little advantage to having one that is only shared between your threads. 
You really need a system-wide connection pool. Alternatively, you might 
find that your database module is thread-safe to the extent that 
different threads can use cursors created on the same connection without 
interference.

If you want each thread to be able to process transactions that are 
invisible to the other threads before they are committed you should 
ensure that you have a sufficient isolation level, which might imply the 
need for a connection-per-thread architecture, in which case you might 
expect some benefit from connection pooling.

regards
  Steve

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline

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


Re: "once" assigment in Python

2007-09-14 Thread Alex Martelli
Lorenzo Di Gregorio <[EMAIL PROTECTED]> wrote:

> When employing Python it's pretty straightforward to translate the
> instance to an object.
> 
> instance = Component(input=wire1,output=wire2)
> 
> Then you don't use "instance" *almost* anymore: it's an object which
> gets registered with the simulator kernel and gets called by reference
> and event-driven only by the simulator kernel.  We might reuse the
> name for calling some administrative methods related to the instance
> (e.g. for reporting) but that's a pretty safe thing to do.  Of course
> all this can be done during initialization, but there are some good
> reasons (see Verilog vs VHDL) why it's handy do be able to do it
> *anywhere*.  The annoying problem was that every time the program flow
> goes over the assignment, the object gets recreated.

If you originally set, e.g.,

  instance = None

then using in your later code:

  instance = instance or Component(...)

will stop the multiple creations.  Other possibilities include using a
compound name (say an.instance where 'an' is an instance of a suitable
container class) and overriding the __new__ method of class Component so
that it will not return multiple distinct objects with identical
attributes.  "Has this *plain* name ever been previously assigned to
anything at all" is simply not a particularly good condition to test for
(you COULD probably write a decorator that ensures that all
uninitialized local variables of a function are instead initialized to
None, but I'd DEFINITELY advise against such "black magic").


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


Re: Just bought Python in a Nutshell

2007-09-14 Thread DouhetSukd
I respectfully disagree with Shawn, in this case.

Don't skim Nutshell, unless you know very little Python, and even then
it is really the wrong book.  It is rather dry reading and provides
very little of the usual user-friendly introductions to language
features by solving simple problems.

Doesn't sound like that much of an endorsement, does it?  Well, in
fact, it is pretty much my most used Python book (out of 7 or 8
others).

If you read Alex's posts in this newsgroup, you'll see that he is one
of the most pragmatic and rigorous posters who usually contributes
code that elegantly and simply solves the issue at hand with the
minimum amount of clutter.

What Python in a Nutshell is really good at is showing you exactly
what Python is capable of doing, feature by feature, in a thoroughly
Pythonic way for the feature.  With code and exact implication.  For
example, I know Python well but I am kinda lacking in metaclass
comprehension.  If I were to write some non-trivial metaclasses I
would surely have his 3 or 4 pages open on my desk as I write code and
skim through other internet postings.  Those 3-4 pages have kinda made
my brain shrivel every time I've looked at them, but they are the
clearest overview I've seen of what is probably one of the hardest
Python features to understand.

For normal, easy-to-understand Python, Nutshell really dissects the
languages with new insight.  The information is dense, because each
word has its place and there very little filler.  That's why skimming
it does not work for me, I just don't have the requisite sustained
attention span.

So, although I read almost all other computer books like Shawn does, I
don't think it applies in this particular case.  When you have a
particular aspect of Python in mind, use Nutshell.  Read up on 'look
before you leap' in it if you really want a sample of how it is
written.

Cheers

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


Re: How to Start

2007-09-14 Thread DouhetSukd
On Sep 13, 4:02 pm, Nikita the Spider <[EMAIL PROTECTED]>
wrote:
> My $.02 for someone such as yourself
> is to deal with Python and as little else as possible. So write your
> code in a simple text editor like UltraEdit or Notepad

Second that opinion.  Use _your_ favorite basic text editor and run on
command line.  Don't clutter your attention with complex tools, yet,
Python's not J2EE for Pete's sake.  I started on Kedit, but mostly use
Eclipse + pydev now, with KEdit as a backup.

Do use one of the interactive interpreters (pythonwin, python prompts,
etc...) to try out one liners and short pieces of code.  But I've
never really liked them for writing full programs.

And I would just do the tutorial or Dive Into Python (http://
www.diveintopython.org/toc/index.html).  If you are as experienced as
you say, you should have very little trouble working through them,
really quickly (3-4 hours?) and you'll have a good tour of the
features.  I picked up Python on a Montreal to Vancouver flight, doing
just that.

For your problem domain.  Modules:  optparse, regular expressions.
Perhaps the "Text Processing in Python" book by Mertz.  I don't like
it much myself, but it does cover text processing in depth and it
refers to a number of existing specialized libraries.

Cheers

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


Re: where is help file?

2007-09-14 Thread Martin Blume
"Carsten Haese" schrieb
> > new to Fedora7, typed python in interactive interpreter, then
help().
> > Then modules to get a list of modules.  Then module name to get
info
> > on a module but no help file.  What is the help file name?
> > Is there an environmental variable I have to set?
>
> There is no help file, and no environment variable. The help text
is
> stored directly inside each module and function that supplies a
help
> text. Observe:
>
> >>> def f(x):
> ...   "Calculate the square of x."
> ...   return x**x
> ...
> >>> help(f)
> Help on function f in module __main__:
>
> f(x)
> Calculate the square of x.
> (END)
>
> Providing such a help text is optional, but all standard library
modules
> do provide help as far as I know. Consequently, the fact that you
have a
> module that doesn't provide a help text seems to indicate that
it's not
> a standard library module. What's the name of the module you're
trying
> to get help on?
>
> Hope this helps (no pun intended),
>
AFAIK you have to import the module first, before you can get help
on that module.

HTH
Martin

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


Re: where is help file?

2007-09-14 Thread Carsten Haese
On Fri, 2007-09-14 at 18:20 +0200, Martin Blume wrote:
> AFAIK you have to import the module first, before you can get help
> on that module.

While that is true of the help(module_name) form, this is not necessary
in the interactive helper you start by calling help().

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Python 3K or Python 2.9?

2007-09-14 Thread Terry Reedy

"Bjoern Schliessmann" <[EMAIL PROTECTED]> wrote 
in message news:[EMAIL PROTECTED]
That's interesting. BTW, do you know something (apart from the dis
docs) that's worth reading if you're interested in Python byte
code?

--
That is the only Python specific thing I remember reading.  Of course, it 
helps that I learned assembler a long time ago, and that I have used an HP 
reverse-polish notation calculator (a fixed-size stack machine), and that I 
have seen and understand algorithms for turning prefix and infix to postfix 
notation.

tjr



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


Re: where is help file?

2007-09-14 Thread Neil Cerutti
On 2007-09-14, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Fri, 2007-09-14 at 18:20 +0200, Martin Blume wrote:
>> AFAIK you have to import the module first, before you can get
>> help on that module.
>
> While that is true of the help(module_name) form, this is not
> necessary in the interactive helper you start by calling
> help().

The interactive help function is cool. You need to download and
install the HTML version of the standard docs to take the utmost
advantage of it.

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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Mark Summerfield
On 14 Sep, 15:35, Antoon Pardon <[EMAIL PROTECTED]> wrote:
[snip]
> I wish you all the luck you can get. Maybe if you succeed I'll change
> my mind about writing a PEP myself.
>
> However I think your chances will increase if you write your module
> and have it available in the cheese shop. If people start using your
> module regularly, your chances of it being included in the standard
> library will increase greatly.

I've taken your advice and put it on PyPI. PyPI isn't as easy to use
as CPAN, and the classifiers don't include "algorithms" or "data
structures" which I find surprising.

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


Re: recursion

2007-09-14 Thread Terry Reedy

"Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|f([1, 2, 3])
| r1  f([2, 3]) + [1]
| r2  f([3]) + [2] + [1]
| r3  f([]) + [3] + [2] + [1]
| r4  [] + [3] + [2] + [1]

I might help to note that the above is effectively parenthesized

( ( ([]+{3]) + [2]) +[1])

*and* that each addition (in each pair of parentheses) is done
in a different execution frame (see below).

| And now the calls return:
|
| r3  [3] + [2] + [1]
| r2  [3, 2] + [1]
| r1  [3, 2, 1]
| > [3, 2, 1]  # how this come here? how python save variables from each
| > recursion?

*Each time* a function is called, an execution frame is created(1) that is 
separate from the function object itself.  Each execution frame has its own 
set of local variables.  In particular, each has its own slices of the 
original list.

There have been languages, for instance, Fortran IV, where local variables 
were part of the function 'object' and which therefore prohibited recursion 
because of the very problem you alluded to in your question.  (My guess is 
the functions had an InUse flag that was checked when the function was 
called.)

tjr

(1) A minor variation would be for function objects to have one 
pre-allocated execution frame for non-recursive calls and others allocated 
as needed for recursive calls. 



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


Re: subclass of integers

2007-09-14 Thread Michael Spencer
Mark Morss wrote:
> I would like to construct a class that includes both the integers and
> None.  I desire that if x and y are elements of this class, and both
> are integers, then arithmetic operations between them, such as x+y,
> return the same result as integer addition.  However if either x or y
> is None, these operations return None.
> 
> It's simple enough to construct a subclass of integers that behave in
> this way:
> 
> class Nint(int):
> def __add__(self,other):
> if (other != None):
> return self+other
> else:
> return None
> def __radd__(self,other):
> if (other != None):
> return other+self
> else:
> return None
> #...and so forth
> 
> However I have not been able to figure out how to make it so that
> None, as well as an integer, could be an element of my class.  My
> preliminary impression is that I have to override int.__new__; but I
> am uncertain how to do that and have been unable to find anything on
> the web explaining that.  Indeed I haven't been able to find much
> about __new__ at all.  Overriding this method of built-in classes
> seems to be quite unusual.
> 
> I would very much appreciate anyone's help.
> 
Do you really need to define one class that can represent None and the 
integers? 
   integers already behave as you want, except that they cannot do binary 
operations with None.  So why not simply define a NoneInt object?

  >>> class NoneInt(object):
  ... def _all_binops(self, other):
  ... if isinstance(other, (int, NoneInt)):
  ... return NoneInt()
  ... else:
  ... raise TypeError()
  ... __add__ = __radd__ = _all_binops
  ... # ...add comparison, unary methods to taste
  ... def __repr__(self):
  ... return "NoneInt()"
  ...
  >>> 3+NoneInt()
  NoneInt()
  >>> NoneInt()+2
  NoneInt()
  >>> "s"+NoneInt()
  Traceback (most recent call last):
File "", line 1, in 
File "", line 6, in _all_binops
  TypeError
  >>>

Getting back to your question, you can indeed override int.__new__ to return 
something other than a raw int.  This explains how and why:
http://www.python.org/download/releases/2.2.3/descrintro/
But unless there's more to your requirement than you set out above, it's 
probably not worth the trouble.

HTH, Michael



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


Re: Coming from Perl - SOLVED

2007-09-14 Thread I V
On Thu, 13 Sep 2007 23:49:32 -0400, Amer Neely wrote:
> In trying to track down why this script would not run on my host, it has
> to come to light that Python is installed, however the Apache module is
> not. So, short story is - I was flogging a dead horse.

Which Apache module? You don't need any special modules (just the regular 
CGI one) to use python in a CGI script.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclass of integers

2007-09-14 Thread Bruno Desthuilliers
Zentrader a écrit :
> This would accept ints, floats, and decimal types.

It doesn't...

> import decimal

Useless

> class Nint(int):
> def __add__(self, x, y):

The prototype for __add__ is __add__(self, other)

> try:
> return x+y
> except:
> return None
> 
> if __name__=='__main__':
> N=Nint()
> print N.__add__( 1, 2 )
> print N.__add__( 1, None )
> print N.__add__(decimal.Decimal("2"), decimal.Decimal("3"))
> print N.__add__(decimal.Decimal("2"), 3)
> 

i = Nint(42)
i + 33
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: __add__() takes exactly 3 arguments (2 given)

The following works better (at least for integers - which is what the OP 
saked for), but it's still not the solution:
import types

class Nint(int):
 def __new__(cls, value=0):
 # doesn't work with Nint(None)...
return int.__new__(cls, value)

 def __add__(self, other):
 if isinstance(other, int):
 return int.__add__(self, other)
 elif isinstance(other, types.NoneType):
 return None
 else:
 err = "unsupported operand type(s) for +: '%s' and '%s'" \
   % (type(self), type(other))
 raise TypeError(err)



i = Nint(42)
=> 42
i + None
=> None
i + "allo"
Traceback (most recent call last):
   File "", line 1, in ?
   File "/usr/tmp/python-8683q3Z", line 19, in __add__
TypeError: unsupported operand type(s) for +: '' 
and ''

Fo some reasons I'm not sure about and didn't have time to investigate 
(some guru around ?), trying to catch a TypeError in __add__ failed - 
raising a TypeError ! But anyway, this isn't the correct solution since 
we don't want Nint.__add__ to return None when other is neither an int 
nor None.

Anyway, this still doesn't solves the OP's problem since it doesn't 
satisfy isinstance(Nint(None), NoneType). I tried making Nint a subclass 
of both int and NoneType, but it doesn't work for obvious reasons (None 
is a singleton). The only funny thing here is the error message when 
trying to call NoneType.__new__:

 >>> NoneType.__new__(NoneType)
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
 >>>


The best I could come with is:

from types import NoneType

class Nint(int, NoneType):
 def __new__(cls, value=None):
# by default, will return Nint(0) even if value is None
 return int.__new__(cls, value)

 def __add__(self, other):
 if isinstance(other, int):
 return int.__add__(self, other)
 elif isinstance(other, NoneType):
 return None
 else:
 err = "unsupported operand type(s) for +: '%s' and '%s'" \
   % (type(self), type(other))
 raise TypeError(err)

# other __functions__ to implement, left as an exercise to the OP

__all__ = [Nint]

Maybe some guru around will find something better, but I have some doubts...



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


Rename multiple files using names in a text file

2007-09-14 Thread rémi
Hi,

I would like to rename files (jpg's ones) using a text file containing the
new names...
Below is the code that doesn't work :
*
#!/usr/bin/python
#-*- coding: utf-8 -*-
from os import listdir, getcwd, rename
import re
list_names=['new_name1','new_name2']
list_files = listdir(getcwd())
filtre = re.compile("jpg$", re.IGNORECASE) 
list_jpg = filter(filtre.search, list_files)
#strip all element of list list_jpg
list_jpg_strip=[]
for nom in list_jpg:
#print nom.strip()
list_jpg_strip.append(nom.strip())
#let's rename :
i=0
while i <= len(list_jpg_strip):
rename(list_jpg_strip[i],list_names[i])
i=i+1

The error message is :
File "ecm.py", line 17, in 
rename(list_jpg_strip[i],list_names[i])
OSError: [Errno 2] No such file or directory
and all files exists, I checked it hundred times ! :-s
Do you have a clue ?
Thanks a lot.
Rémi.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: subclass of integers

2007-09-14 Thread Bruno Desthuilliers
Mark Morss a écrit :
> I would like to construct a class that includes both the integers and
> None.   I desire that if x and y are elements of this class, and both
> are integers, then arithmetic operations between them, such as x+y,
> return the same result as integer addition.  However if either x or y
> is None, these operations return None.
> 
> It's simple enough to construct a subclass of integers that behave in
> this way:
> 
> class Nint(int):
> def __add__(self,other):
> if (other != None):
> return self+other
> else:
> return None
> def __radd__(self,other):
> if (other != None):
> return other+self
> else:
> return None
> #...and so forth
> 
> However I have not been able to figure out how to make it so that
> None, as well as an integer, could be an element of my class.  My
> preliminary impression is that I have to override int.__new__; but I
> am uncertain how to do that and have been unable to find anything on
> the web explaining that.  Indeed I haven't been able to find much
> about __new__ at all.  Overriding this method of built-in classes
> seems to be quite unusual.
> 
> I would very much appreciate anyone's help.

You'll find documentation in the FineManual(tm):
http://docs.python.org/ref/customization.html
http://www.python.org/download/releases/2.2.3/descrintro/#__new__

and a possible (even if imperfect IMHO) example in my answer to 
Zentrader in the thread.

Now would you be kind enough to satisfy my curiousity and explain your 
use case ?-)


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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread James Stroud
Mark Summerfield wrote:
> So to clarify, here's the entire API I'm proposing for ordereddict. In
> all cases the ordereddict is always in (and kept in) key order, and
> any method that returns a list or iterator always returns that list or
> iterator (whether of keys or values) in key order:
> 
> ordereddict(dictionary=None)
> The argument can be a dict or another ordereddict; all the dict()
> initializer
> approaches should also be supported.
> 
> ordereddict.update(dictonary=None, **kwargs)
> Same as dict.update()---except that key order is preserved (a
> point I won't
> repeat in the others when I say "same as dict", but which is true
> throughout)
> 
> @classmethod
> ordereddict.fromkeys(cls, iterable, value=None) # Same as dict
> 
> ordereddict.key(index : int) -> key
> Returns the index-th item's key
> 
> ordereddict.item(index : int) -> (key, value)
> Returns the index-th item
> 
> ordereddict.value(index : int) -> value
> Returns the index-th item's value
> 
> ordereddict.set_value(index : int, value)
> Sets the index-th item's value to value; raises IndexError if
> index is out of
> range. If not expensive, maybe return the key.
> 
> ordereddict.copy() # Same as dict.
> ordereddict.clear() # Same as dict.
> ordereddict.get(key, value=None) # Same as dict
> ordereddict.setdefault(key, value) # Same as dict
> ordereddict.pop(key, value) # Same as dict
> ordereddict.popitem() # Same as dict
> 
> ordereddict.keys(fromindex : int = None, uptoindex : int : None) ->
> list of keys
> Returns an ordered list of keys, or a slice of keys if one or two
> indexes is given
> 
> ordereddict.values() # Same as dict
> ordereddict.items() # Same as dict
> ordereddict.iterkeys() # Same as dict
> ordereddict.itervalues() # Same as dict
> ordereddict.iteritems() # Same as dict
> ordereddict.has_key() # Same as dict
> 
> Also the same as dict (and as always, working in key order):
> 
> for key in d: pass
> if key in d: pass
> len(d)
> del d[key]
> d[key]
> d[key] = value

May I also make one more suggestion, to call it a "sort_ordered_dict" 
(or "sortordereddict", or even better a "sorteddict"--where the "ed" 
comes from "ordered")? Its hard for me to move past the established 
definition of "order", as we think of tuples being ordered--as in the 
first sentence of http://en.wikipedia.org/wiki/Tuple--to something that 
is preserving an order according to a comparison. The distinction is so 
firmly ingrained in my head that it took me a while to wake up to the 
fact that you were describing something completely different than an 
ordered dictionary (e.g. http://www.voidspace.org.uk/python/odict.html) 
even though you were being very unambiguous with your description.

And I also think the ability to drop it in for a built-in dict is very 
valuable.

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


Re: Rename multiple files using names in a text file

2007-09-14 Thread James Stroud
rémi wrote:
> Hi,
> 
> I would like to rename files (jpg's ones) using a text file containing the
> new names...
> Below is the code that doesn't work :
> *
> #!/usr/bin/python
> #-*- coding: utf-8 -*-
> from os import listdir, getcwd, rename
> import re
> list_names=['new_name1','new_name2']
> list_files = listdir(getcwd())
> filtre = re.compile("jpg$", re.IGNORECASE) 
> list_jpg = filter(filtre.search, list_files)
> #strip all element of list list_jpg
> list_jpg_strip=[]
> for nom in list_jpg:
>   #print nom.strip()
>   list_jpg_strip.append(nom.strip())
> #let's rename :
> i=0
> while i <= len(list_jpg_strip):
>   rename(list_jpg_strip[i],list_names[i])
>   i=i+1
> 
> The error message is :
> File "ecm.py", line 17, in 
> rename(list_jpg_strip[i],list_names[i])
> OSError: [Errno 2] No such file or directory
> and all files exists, I checked it hundred times ! :-s
> Do you have a clue ?
> Thanks a lot.
> Rémi.

Other than that your strip() is stripping off some whitespace that is 
part of the name, I really can't see the problem either, but did you try 
to add in the explicit path? E.g.:

path_to = getcwd()
list_files = listdir(path_to)
.
.
.
for nom in list_jpg:
   old_path = os.path.join(path_to, nom.strip())
   list_jpg_strip.append(old_path)
.
.
.
for old_path, new_name in zip(list_jpg_strip, list_names):
   new_path = os.path.join(path_to, new_name)
   rename(old_path, new_path)

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

Https conversation - debug?

2007-09-14 Thread Johny
Is there any good sniffer for https protocol?
How can be watched https conversation?

Thanks for reply
L.

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


Re: Https conversation - debug?

2007-09-14 Thread Jarek Zgoda
Johny napisał(a):

> Is there any good sniffer for https protocol?
> How can be watched https conversation?

Any packet sniffer will do. Then you have to decrypt the stream. ;)

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An ordered dictionary for the Python library?

2007-09-14 Thread Mark Summerfield
On 14 Sep, 20:25, James Stroud <[EMAIL PROTECTED]> wrote:
> Mark Summerfield wrote:
[snip]
> May I also make one more suggestion, to call it a "sort_ordered_dict"
> (or "sortordereddict", or even better a "sorteddict"--where the "ed"
> comes from "ordered")? Its hard for me to move past the established
> definition of "order", as we think of tuples being ordered--as in the
> first sentence ofhttp://en.wikipedia.org/wiki/Tuple--tosomething that
> is preserving an order according to a comparison. The distinction is so
> firmly ingrained in my head that it took me a while to wake up to the
> fact that you were describing something completely different than an
> ordered dictionary (e.g.http://www.voidspace.org.uk/python/odict.html)
> even though you were being very unambiguous with your description.
>
> And I also think the ability to drop it in for a built-in dict is very
> valuable.
>
> James

It seems that the correct Python terminology for this is indeed
sorteddict (ordered by key), with ordereddict meaning (in insertion
order).

I guess I'll have to rename my module (although unfortunately, my book
has just gone into production and I have a (simpler) example of what I
considered to be an ordered dict, so I will be adding to the
terminology confusion). That notwithstanding, given that it is a
sorteddict, how is the API?

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


Re: Just bought Python in a Nutshell

2007-09-14 Thread Lamonte Harris
Right, I like reading books it comes handier then reading ebooks,  less
programs and its right there in your hands.  Main reason I'm going to use it
for is to find questions without asking them on the python list or tutor
list for a quicker referrence.

On 9/14/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> I respectfully disagree with Shawn, in this case.
>
> Don't skim Nutshell, unless you know very little Python, and even then
> it is really the wrong book.  It is rather dry reading and provides
> very little of the usual user-friendly introductions to language
> features by solving simple problems.
>
> Doesn't sound like that much of an endorsement, does it?  Well, in
> fact, it is pretty much my most used Python book (out of 7 or 8
> others).
>
> If you read Alex's posts in this newsgroup, you'll see that he is one
> of the most pragmatic and rigorous posters who usually contributes
> code that elegantly and simply solves the issue at hand with the
> minimum amount of clutter.
>
> What Python in a Nutshell is really good at is showing you exactly
> what Python is capable of doing, feature by feature, in a thoroughly
> Pythonic way for the feature.  With code and exact implication.  For
> example, I know Python well but I am kinda lacking in metaclass
> comprehension.  If I were to write some non-trivial metaclasses I
> would surely have his 3 or 4 pages open on my desk as I write code and
> skim through other internet postings.  Those 3-4 pages have kinda made
> my brain shrivel every time I've looked at them, but they are the
> clearest overview I've seen of what is probably one of the hardest
> Python features to understand.
>
> For normal, easy-to-understand Python, Nutshell really dissects the
> languages with new insight.  The information is dense, because each
> word has its place and there very little filler.  That's why skimming
> it does not work for me, I just don't have the requisite sustained
> attention span.
>
> So, although I read almost all other computer books like Shawn does, I
> don't think it applies in this particular case.  When you have a
> particular aspect of Python in mind, use Nutshell.  Read up on 'look
> before you leap' in it if you really want a sample of how it is
> written.
>
> Cheers
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

why does Configparser change names to lowercase ?

2007-09-14 Thread stef mientki
hello,

Why does  Configparser change names to lowercase ?

As Python is case sensitive (which btw I don't like at all ;-)
but now when really need the casesensitivity,
because it handles about names which should be recognized by human,
it changes everything to lowercase 

thanks,
Stef Mientki


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


Re: An ordered dictionary for the Python library?

2007-09-14 Thread James Stroud
Mark Summerfield wrote:
> I guess I'll have to rename my module (although unfortunately, my book
> has just gone into production and I have a (simpler) example of what I
> considered to be an ordered dict, so I will be adding to the
> terminology confusion). That notwithstanding, given that it is a
> sorteddict, how is the API?

I must think the API good because I have been implementing, in parallel 
with this discussion, my own "OrderedDict" with a very similar API (this 
is part of a larger project where I recently found the need to have a 
well-implemented ordered dict). The only real omission I see is to allow 
instantiating a "sorted dict" with an optional cmp function--to allow 
the generalization of such features as case-independence, etc.

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


Re: How to Start

2007-09-14 Thread James Stroud
Paul McGuire wrote:
> Do "neophytes" just dive in and try stuff?

I think a lot of us coming from other fields actually slithered in, in 
true python style.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why does Configparser change names to lowercase ?

2007-09-14 Thread James Stroud
stef mientki wrote:
> hello,
> 
> Why does  Configparser change names to lowercase ?

Because it is an annoying module and should be tossed for something 
better? Try this instead (and never look back):

   http://www.voidspace.org.uk/python/configobj.html


> As Python is case sensitive (which btw I don't like at all ;-)
> but now when really need the casesensitivity,
> because it handles about names which should be recognized by human,
> it changes everything to lowercase 

So you are saying the case sensitivity is a good thing--or maybe you are 
still running Mac System 7 on your CSIIsi marveling at the wonders of HFS?

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


Make money to share your videos

2007-09-14 Thread earnloads007

Goodtolove.com is sharing their 50% adsense revenue with you to post
videos of anything.
Just keep up logging in and start posting now to make money...

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


Re: subclass of integers

2007-09-14 Thread Ian Clark
Mark Morss wrote:
> I would like to construct a class that includes both the integers and
> None.  I desire that if x and y are elements of this class, and both
> are integers, then arithmetic operations between them, such as x+y,
> return the same result as integer addition.  However if either x or y
> is None, these operations return None.
> 
> It's simple enough to construct a subclass of integers that behave in
> this way:
> 
> class Nint(int):
> def __add__(self,other):
> if (other != None):
> return self+other
> else:
> return None
> def __radd__(self,other):
> if (other != None):
> return other+self
> else:
> return None
> #...and so forth
> 
> However I have not been able to figure out how to make it so that
> None, as well as an integer, could be an element of my class.  My
> preliminary impression is that I have to override int.__new__; but I
> am uncertain how to do that and have been unable to find anything on
> the web explaining that.  Indeed I haven't been able to find much
> about __new__ at all.  Overriding this method of built-in classes
> seems to be quite unusual.
> 
> I would very much appreciate anyone's help.

My thought would be rather than trying to cram None into a subclass of 
int, to use delegation instead...

-8<--
class NoneInt(object):
 def __init__(self, value):
 self.value = value

 def __add__(self, other):
 if isinstance(other, NoneInt):
 if None in (self.value, other.value):
 return NoneInt(None)
 return NoneInt(self.value + other.value)
 elif isinstance(other, int):
 if self.value is None:
 return NoneInt(None)
 return NoneInt(self.value + other)
 else:
 raise TypeError(
 "unsupported operand type(s) for +: 'NoneInt'"
 "and '%s'" % str(other.__class__.__name__)
 )
 __radd__ = __add__

 def __str__(self):
 return 'NoneInt(%s)' % str(self.value)


def main():
 print '42? ', NoneInt(40) + NoneInt(2)
 print '41? ', NoneInt(40) + 1
 print '40? ', 25 + NoneInt(15)
 print 'None? ', NoneInt(None)
 print 'None? ', NoneInt(None) + 1
 print 'None? ', 1 + NoneInt(None)
 print 'Error? ', NoneInt(0) + 'spam'

if __name__ == '__main__':
 main()
-8<--

Ian

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


regexp search on infinite string?

2007-09-14 Thread Paddy
Lets say i have a generator running that generates successive
characters of a 'string'
>From what I know, if I want to do a regexp search for a pattern of
characters then I would have to 'freeze' the generator  and pass the
characters so far to re.search.
It is expensive to create successive characters, but caching could be
used for past characters. is it possible to wrap the generator in a
class, possibly inheriting from string, that would allow the regexp
searching of the string but without terminating the generator? In
other words duck typing for the usual string object needed by
re.search?

- Paddy.

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


Re: 2 daemons write to a single file /w python file IO

2007-09-14 Thread Steven W. Orr
On Tuesday, Sep 11th 2007 at 21:17 -0700, quoth Andrey:


=>i have a newbie question about the file() function.
=>I have 2 daemons running on my linux box.
=>
=>1 will record the IDs to a file - logs.txt
=>other 1 will open this file, read the IDs, and then "Clean up the 
=>file" -logs.txt
=>
=>Since these 2 daemons will run every 2-5mins, I think this will crash, isn't 
=>it? When both daemons try to write to the file at the same time.
=>
=>I am wondering if this won't crash, OR if there is some simple high-level 
=>functions can lock the file while writing...
=>I also wonder if one side locked the file, what happens if the other side 
=>try to open this locked file? raise error? so i also need to write a loop to 
=>wait for the file to release locking?
=>
=>seems a basic easy thing but i just cannot find an simple answer.
=>I always advoid this issue by putting them in mysql (well, fast and hassle 
=>free for locking)

This is more of a unix question as opposed to a python question, but I'll 
'splain it anyways :-)

If two processes each have a channel opened to the same file then it is 
very possible for the writes to collide. One way to mitigate the damage 
would be to make sure that the two processes open the file for append 
access instead of simple write access. This will ensure that the if 
ProcessA writes data that ProcessB's next write won't overwrite the data 
that A just wrote. But! It still won't work! You will still get 
interleaving of data in your output file. They will all get out there, but 
the data will on occasion look garbled because the interleaving won't look 
like it was partitioned as the different processes intended.

So what's the solution? It turns out that data that is written to a pipe 
(as opposed to data that is written to a file) is guaranteed to maintain 
its partitioned integrity.

P1 >> fn
P2 >> fn

If you are the guy who starts P1 and P2 from a parent process(PP) then you 
could structure your pipes so you end up with 

  PP > fn
 / \
/   \
   P1   P2

and just make PP be a multiplexor.  :-)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why does Configparser change names to lowercase ?

2007-09-14 Thread Rob Wolfe
stef mientki <[EMAIL PROTECTED]> writes:

> hello,
>
> Why does  Configparser change names to lowercase ?
>
> As Python is case sensitive (which btw I don't like at all ;-)
> but now when really need the casesensitivity,
> because it handles about names which should be recognized by human,
> it changes everything to lowercase 

I don't know why, but I know how to change it and I found the solution here:
http://docs.python.org/lib/RawConfigParser-objects.html

You need to change the implementation of method `optionxform`, e.g.:

# config
[section1]
option1=item1
Option2=item2
option2=item3

# cfg.py
from ConfigParser import ConfigParser

config = ConfigParser()
config.optionxform = str
config.read('config')
print config.get('section1', 'option1')
print config.get('section1', 'Option2')
print config.options('section1')

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


Re: Just bought Python in a Nutshell

2007-09-14 Thread Danyelle Gragsone
Luckily that site still had one left .. so i brought it :D.  I can
always use another good and CHEAP book.

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


Re: where is help file?

2007-09-14 Thread PaulS
Thanks everyone.
Paul


"Neil Cerutti" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On 2007-09-14, Carsten Haese <[EMAIL PROTECTED]> wrote:
>> On Fri, 2007-09-14 at 18:20 +0200, Martin Blume wrote:
>>> AFAIK you have to import the module first, before you can get
>>> help on that module.
>>
>> While that is true of the help(module_name) form, this is not
>> necessary in the interactive helper you start by calling
>> help().
>
> The interactive help function is cool. You need to download and
> install the HTML version of the standard docs to take the utmost
> advantage of it.
>
> -- 
> Neil Cerutti 


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


Re: Python 3K or Python 2.9?

2007-09-14 Thread John Roth
On Sep 12, 11:35 am, TheFlyingDutchman <[EMAIL PROTECTED]> wrote:
> On Sep 12, 4:40 am, Bjoern Schliessmann <[EMAIL PROTECTED]> wrote:
> > Ivan Voras wrote:
> > > What does "self" have to do with an object model? It's an
> > > function/method argument that might as well be hidden in the
> > > compiler without ever touching the role it has (if not, why?). I
> > > agree that it's needless noise in a language.
>
> > If this was needless, why do C++ and Java have the "this" pointer?
>
> "this" in C++ and Java is not shown in the parameter list, which was
> what he was
> complaining about.  He wants
>
> class MyClass:
> def SomeFunction(someParameter):
>self.someParameter = someParameter
>
> not
>
> class MyClass:
> def SomeFunction(self, someParameter):
>self.someParameter = someParameter
>
> The confusing way about the current Python method when you first
> encounter it is
>  why is "self" being passed in when you write the function but not
> when you call it. If the compiler is smart enough to know that
>
> a = MyClass()
> a.SomeFunction(12)
>
> SomeFunction() has a "self" implicitly added to the parameter list, it
> seems that it should be smart enough to know that a function defined
> in a class has a "self" implicitly added to the parameter list.

Pretty close. This is one of the things that's always puzzled me about
the discussion. Making self and cls keyword pseudo-constants that get
the current instance and class from the stack frame (or raise an
exception) would eliminate them from the method header.

It would ALSO eliminate a whole level of indirection in method
invocation and get rid of the instancemethod, classmethod and
staticmethod wrapper classes. This would be a significant
simplification. If it had been done earlier, it would have eliminated
most of the justification for method attributes (those silly @
things), thus showing that unneeded complexity breeds more unneeded
complexity.

John Roth

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


Re: recursion

2007-09-14 Thread John Machin
On Sep 15, 3:06 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
> There have been languages, for instance, Fortran IV, where local variables
> were part of the function 'object' and which therefore prohibited recursion
> because of the very problem you alluded to in your question.  (My guess is
> the functions had an InUse flag that was checked when the function was
> called.)

No way. Waste of space for instructions to check the flag at the start
and reset it at the end. Waste of CPU time. Divide by zero? Subroutine
calls itself? Drive against the traffic flow on the freeway? Expected
outcome: crash or other unwanted result. Simple: don't do that! Why
bother checking? No self-respecting FORTRAN programmer would want to
use recursion anyway. And mixed case in a variable name? Sheesh.

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


reading xls file from python

2007-09-14 Thread hassen62
hi friends, 
I have installed python 2.5 for windows in my pc, I have a file xls say 
"file.xls" in c:/python25. How I can read this files from Python. Many thanks 
in advance.
Hassen.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: subclass of integers

2007-09-14 Thread Ian Clark
Ian Clark wrote:
> Mark Morss wrote:
>> I would like to construct a class that includes both the integers and
>> None.  I desire that if x and y are elements of this class, and both
>> are integers, then arithmetic operations between them, such as x+y,
>> return the same result as integer addition.  However if either x or y
>> is None, these operations return None.
>>
>> (snip)
>>
>> I would very much appreciate anyone's help.
> 
> My thought would be rather than trying to cram None into a subclass of 
> int, to use delegation instead...
> 
> (snip)
> 
> Ian

A more robust implementation that accounts for ints/longs as well as 
implementing more operations...

-8<--
import operator

class NoneInt(object):
 _LEFT = 1
 _RIGHT = 2


 def __init__(self, value):
 self.value = value


 def _get_arguments(self, other, direction=_LEFT):
 """ Given a direction (left or right), returns the left hand
 side and right hand side values. """

 if direction == self._LEFT:
 lhs = self.value
 if isinstance(other, (int, long, type(None))):
 rhs = other
 else:
 rhs = other.value
 elif direction == self._RIGHT:
 rhs = self.value
 if isinstance(other, (int, long, type(None))):
 lhs = other
 else:
 lhs = other.value
 else:
 raise ValueError('direction must be either _LEFT or _RIGHT')
 return (lhs, rhs)


 def _operation(op, direction):
 """ Given a direction and an operation will return a function
 that calls the operation with the arguments in the correct
 order. """

 def func(self, other):
 if not isinstance(other, (int, long, NoneInt, type(None))):
 fmt = "unsupported operand type(s) for %s: 'NoneInt' 
and '%s'"
 args =  (op.__name__, other.__class__.__name__)
 raise TypeError(fmt % args)

 lhs, rhs = self._get_arguments(other, direction)

 if None in (lhs, rhs):
 return NoneInt(None)
 return NoneInt(op(lhs, rhs))
 return func


 __add__ = _operation(operator.add, _LEFT)
 __radd__ = _operation(operator.add, _RIGHT)
 __sub__ = _operation(operator.sub, _LEFT)
 __rsub__ = _operation(operator.sub, _RIGHT)
 __div__ = _operation(operator.div, _LEFT)
 __rdiv__ = _operation(operator.div, _RIGHT)
 __mul__ = _operation(operator.mul, _LEFT)
 __rmul__ = _operation(operator.mul, _RIGHT)
 # ... etc


 def __eq__(self, other):
 lhs, rhs = self._get_arguments(other)
 return lhs == rhs


 def __nonzero__(self):
 return bool(self.value)


 def __str__(self):
 return 'NoneInt(%s)' % str(self.value)

 __repr__ = __str__
-8<--

Ian

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


Re: Spaces from string specifier

2007-09-14 Thread Ian Clark
Gabriel Genellina wrote:
> En Fri, 14 Sep 2007 01:57:43 -0300, Gavin Tomlins <[EMAIL PROTECTED]>  
> escribi�:
> 
>> I'm trying to work out when using a format specifier I get spaces in the
>> resulting string.  Eg. Looking at the outputted string you can see that
>> there are spaces after T5LAT, F4LAT etc. as I result from trying to keep  
>> the
>> code aligned
> 
> - You should *not* build the SQL text yourself; use a parametrised query  
> instead. It's not only easier to write; it's safer, less error prone, and  
> maybe faster. See this previous post  
> 
> 
> - Spaces are not significant in SQL, but you may have your own reasons to  
> format the SQL text in a certain way. In addition to the ideas already  
> menctioned on that thread (avoid \, use parenthesis, and auto-concatenate  
> adjacent strings), you may use a triple-quoted string + function dedent  
>  from textwrap module:
> 
> py> fmtSqlP300Amp = textwrap.dedent('''\
> ...   UPDATE Patient SET
> ... O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s",
> ... P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s",
> ... TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s"
> ...   WHERE Pat_Id = "%s"''')
> py> print fmtSqlP300Amp
> UPDATE Patient SET
>O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s",
>P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s",
>TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s"
> WHERE Pat_Id = "%s"
> 
> I hope any of these ideas will fit your own needs.

Completely agree that this should not be written by hand. But if you 
absolutely *must* you might try something like this:

 >>> fmt = """
 ... UPDATE Patient SET
 ... 02AMP = "%(o2amp)s"
 ... O1AMP = "%(o1amp)s"
 ... ...
 ... """
 >>> args = {
 ... 'o1amp': "2.77413",
 ... 'o2amp': "2.43119"
 ... }
 >>> print fmt % args

 UPDATE Patient SET
 02AMP = "2.43119"
 O1AMP = "2.77413"
 ...

 >>>

Ian

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

Re: Python 3K or Python 2.9?

2007-09-14 Thread George Sakkis
On Sep 12, 1:35 pm, TheFlyingDutchman <[EMAIL PROTECTED]> wrote:

> On Sep 12, 4:40 am, Bjoern Schliessmann <[EMAIL PROTECTED]> wrote:
> > Ivan Voras wrote:
> > > What does "self" have to do with an object model? It's an
> > > function/method argument that might as well be hidden in the
> > > compiler without ever touching the role it has (if not, why?). I
> > > agree that it's needless noise in a language.
>
> > If this was needless, why do C++ and Java have the "this" pointer?
>
> "this" in C++ and Java is not shown in the parameter list, which was
> what he was
> complaining about.  He wants
>
> class MyClass:
> def SomeFunction(someParameter):
>self.someParameter = someParameter
>
> not
>
> class MyClass:
> def SomeFunction(self, someParameter):
>self.someParameter = someParameter

If one *really* wants this, it is doable in python too:
http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_16.shtml#e583

George

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


Re: List Comprehension Question: One to Many Mapping?

2007-09-14 Thread beginner
On Aug 24, 5:35 am, Boris Borcic <[EMAIL PROTECTED]> wrote:
> Paul Rubin wrote:
> > beginner <[EMAIL PROTECTED]> writes:
> >> For example, if I have x=[ [1,2], [3,4] ]
>
> >> What I want is a new list of list that has four sub-lists:
>
> >> [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]]
>
> > [[a, map(f,a)] for a in x]
>
> no, that one will be [[[1,2], [f(1), f(2)]], [[3,4], [f(3), f(4)]]]
> eg two sublists instead of four.
>
> [map(g,a) for a in x for g in [None,f]]
>
> will do it.
>
> ...a bit too cleverly, but there's worse :
>
> list((yield a) or map(f,a) for a in x)
>
> Cheers, BB

Really cool!

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


Re: subclass of integers

2007-09-14 Thread Dan Bishop
On Sep 14, 9:30 am, Mark Morss <[EMAIL PROTECTED]> wrote:
> I would like to construct a class that includes both the integers and
> None.  I desire that if x and y are elements of this class, and both
> are integers, then arithmetic operations between them, such as x+y,
> return the same result as integer addition.  However if either x or y
> is None, these operations return None.

Rather than subclassing int, why not just make a singleton NaN object
with overloaded arithmetic operators that all return NaN?

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


Re: Extended slicing and Ellipsis - where are they used?

2007-09-14 Thread James Stroud
Paddy wrote:
> And the ellipses ... ?

;)


py> class Bob(dict):
...   def __getitem__(self, k, *args, **kwargs):
... if k is Ellipsis:
...   return sorted(self.keys())
... else:
...   return dict.__getitem__(self, k, *args, **kwargs)
...   def __setitem__(self, k, *args, **kwargs):
... if k is Ellipsis:
...   raise KeyError, "Can't make elliptical assignments."
... else:
...   return dict.__setitem__(self, k, *args, **kwargs)
...
py> b = Bob(a=1, b=2, c=3, d=15.5)
py> b
{'a': 1, 'b': 2, 'c': 3, 'd': 15.5}
py> for k in b[...]:
   print '%s ==> %s' % (k, b[k])
...
a ==> 1
b ==> 2
c ==> 3
d ==> 15.5
py> b[...] = 2

Traceback (most recent call last):
   File "", line 1, in 
   File "", line 9, in __setitem__
: "Can't make elliptical assignments."
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there some sort of Python Error log.

2007-09-14 Thread Lamonte Harris
Command prompt is a pain and it would be pretty nice to have this feature.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Car-ac-systems

2007-09-14 Thread Arne Vajhøj
[text reordered from top post to standard newsgroup style]

John Timney (MVP) wrote:
> <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> On Sep 11, 9:35 am, "John Timney \(MVP\)"
>> <[EMAIL PROTECTED]> wrote:
>>> How do I control one with C# then!  Thats not on your site, clearly not
>>> everything I need to know then.  Waste of a site!
>> C# is just as off topic in comp.lang.java.programmer as car air-
>> conditioning systems. The latter, however, have the redeeming
>> characteristic that they are not the demonic spawn of evil Microsoft.
 > ho ho..now thats quite funny!

Before you start wondering too much try and make a search in
comp.lang.java.programmer for posts by nebulous99 ...

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


Re: Https conversation - debug?

2007-09-14 Thread Bjoern Schliessmann
Johny wrote:

> Is there any good sniffer for https protocol?

Yes.

> How can be watched https conversation?

As a matter of principle, with every working sniffer. I'd use
wireshark's "follow TCP stream" function.

Regards,


Björn

-- 
BOFH excuse #198:

Post-it Note Sludge leaked into the monitor.

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


  1   2   >