Re: How can i use a variable without define it ?

2008-07-18 Thread Tim Roberts
zhw [EMAIL PROTECTED] wrote:
Ben Finney [EMAIL PROTECTED] wrote:

 What problem are you trying to solve?

I an sorry, I can't tell you.

That's nonsense.  No one is asking you to reveal the design of your
company's next product.  However, you have some overall problem you are
trying to solve, and you have focused in on one POSSIBLE solution. Instead,
tell us about the PROBLEM, and we'll offer good solutions.

If you can't give a solution, just ignore it!

NO ONE will be able to give you a solution, because you have not described
the problem.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: % sign in python?

2008-07-18 Thread Tim Roberts
Steven Howe [EMAIL PROTECTED] wrote:

Terry Reedy wrote:

 korean_dave wrote:
 What does this operator do? Specifically in this context

 test.log( [[Log level %d: %s]] % ( level, msg ), description )

I thought, in this contexted, it was  mapping operator.

What??

Python does not have a mapping operator.  It has a map function, but no
equivalent operator.

% is either the string formatting operator (when the left-hand operand is a
string) or the modulo operator (when the left-hand operand is a number).
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: storing references instead of copies in a dictionary

2008-07-18 Thread castironpi
On Jul 17, 7:36 pm, bgeddy [EMAIL PROTECTED] wrote:
 bgeddy wrote:
  castironpi wrote:
  On Jul 17, 10:05 am, mk [EMAIL PROTECTED] wrote:
  def f2(arg):
      return f2 +arg
  def f1(arg):
      return f1 +arg
  a={1:f1,2:f2}
  print [eval(x[1])(x[0]) for x in a.items()]
  def f2(arg):
      return New f2 +arg
  print [eval(x[1])(x[0]) for x in a.items()]
  Neat trick, if probably dangerous in some circumstances. Anyway, thanks,
  I didn't think of that.

  Don't know if this is any use to you..
  At least I learned something. :-)

  You want consistent access to a changing variable.  Wrap it in an
  object:

  a= Blank( )
  a.ref= 'X'
  a.ref
  'X'
  b= a
  b.ref
  'X'
  a.ref= 'Y'
  b.ref
  'Y'

  My old fashioned programing paradigms think of this in terms of
  pointers, a throw back to my schooling in 'C'. I find this general
  form of problem to be common across languages and in some ways hard to
  express in python. The whole idea of labels bound to objects is quite
  alien to traditional terminology. I find one of the main attractions of
  python is this new mindset that the language makes you adopt - a
  different set of tools are at hand for the old school programmer.

  castironpi - please give an example of what you are thinking as I find
  this interesting. preferably post some brief example code.

 castironpi  - please forgive the double post but my newsreader didn't
 display your code correctly.. Doh !! Anyway - a nice way of addressing
 the problem. However the OP's post revolved around having a rewritable
 set of labels - which could be recorded at one time and when re
 referenced the new definitions of those labels would be used. For
 example a collection (list,dictionary,tuple) could be made of these
 labels and then the underlying code accessed by the labels changed. If
 the code was now ran indirectly by referencing the list then the new
 code would be ran. These building blocks are how parsers are built and
 the basis of language.
 I can see how you form two ways of addressing the variable but can't
 figure how this fits the original problem. Please elaborate for my
 ignorance.

 EdH.

In the OP's post, we have:

def f1(): print 'f1'
def f2(): print 'f2'
funs= [ f1, f2 ]
def f1(): print 'new f1'

They wanted funs[ 0 ] to contain this new function / new definition
too.

Another language might permit:
def funs[ 0 ](): print 'new f1'

Python allows:

def f1(): print 'new f1'
funs[ 0 ]= f1

and

@rebind( funs, 0 )
def f1(): print 'new f1'

and

@rebind_named( funs, 'funA' )
def f1(): print 'new f1'

in the case funs was a dictionary or class or class instance.
Functions remain to be first class objects; their definition syntax is
merely restricted over normal assignments.

To access whatever 'f1' is pointing to right now, the only way is
with eval, which you showed.

Spealman's solution can accomplish redefinition, but only provided
calling signature and closure, among others, don't change.  If they
do, you have to reassign those, too, and possibly more:

 dir( f )
[snip]
'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc',
'func_globals', 'func_name'

Roughly the same in 3.0.  It's an option.

 These building blocks are how parsers are built and
 the basis of language.

To address this, I observe altered references are easy for computers.
Suppose:

#--NOT PYTHON--
def f1(): print 'f1'
008902 f1:  0x008934
def f1(): print 'new f1'
008902 f1:  0x008938

'f1()' calls the function the address of which is stored at 008902 in
each case: f1 (at 008934) in the first case, and new f1 (at 008938) in
the second.

Python eliminates that combination from the syntax, which strengthens
object-name identity, at the cost of a slightly longer workaround
(a.ref= f1) for keeping names but changing objects.  In this sense,
the only 'pointer' per se is the string name of an object, scoped by a
namespace-- eval( 'f1', spaceA ).

I delicately ask for an example in natural language and daily life in
which we change what object a name refers to, or hold that Python
conforms to natural language better than computer-native mutable
pointers and references.
--
http://mail.python.org/mailman/listinfo/python-list


Re: interpreter vs. compiled

2008-07-18 Thread castironpi
On Jul 17, 11:39 pm, Kay Schluehr [EMAIL PROTECTED] wrote:
 On 18 Jul., 01:15, castironpi [EMAIL PROTECTED] wrote:



  On Jul 17, 5:37 pm, I V [EMAIL PROTECTED] wrote:

   On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote:
The Python disassembly is baffling though.

y= 3
dis.dis('x=y+1')

   You can't disassemble strings of python source (well, you can, but, as
   you've seen, the results are not meaningful). You need to compile the
   source first:

code = compile('y=x+1','-', 'single')
dis.dis(code)

     1           0 LOAD_NAME                0 (x)
                 3 LOAD_CONST               0 (1)
                 6 BINARY_ADD
                 7 STORE_NAME               1 (y)
                10 LOAD_CONST               1 (None)
                13 RETURN_VALUE

   You may well find these byte codes more meaningful. Note that there is a
   list of opcodes athttp://docs.python.org/lib/bytecodes.html

  Oh.  How is the stack represented?

 As a pointer to a pointer of PyObject structs.

  Does it keep track of which stack
  positions (TOS, TOS1, etc.) are in what registers?  Does stack
  manipulation consume processor cycles?

 Python does not store values in registers. It stores locals in arrays
 and accesses them by position ( you can see the positional index in
 the disassembly right after the opcode name ) and globals / object
 attributes in dicts.

 For more information you might just download the source distribution
 and look for src/Python/ceval.c. This file contains the main
 interpreter loop.

Oh.  I was interpreting, no pun, that the column of numbers to the
left indicated how many processor cycles were consumed in each
operation.  It doesn't quite make sense, unless BINARY_ADD can refer
to memory outside of the registers, which I doubt on the basis that
two addresses would have to fit into a single operation, plus the
architecture opcode.  Given that, what does that column indicate?

I'm intimidated by the source but I may look.
--
http://mail.python.org/mailman/listinfo/python-list


Re: storing references instead of copies in a dictionary

2008-07-18 Thread John Machin
On Jul 18, 4:26 pm, castironpi [EMAIL PROTECTED] wrote:
 I delicately ask for an example in natural language and daily life in
 which we change what object a name refers to,

her, him, it, ... i.e. any pronoun
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to process a very large (4Gb) tarfile from python?

2008-07-18 Thread Uwe Schmitt
On 17 Jul., 22:21, Lars Gustäbel [EMAIL PROTECTED] wrote:

  Maybe we should post this issue to python-dev mailing list.
  Parsing large tar-files is not uncommon.

 This issue is known and was fixed for Python 3.0, 
 seehttp://bugs.python.org/issue2058.

The proposed patch does not avoid caching the previous values of the
iterator, it just
reduces the size of each cached object.
It would be nice to be able to avoid caching on demand, which would
make
iteration independent of the size of the tar file.

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


None in comparison

2008-07-18 Thread r . grimm
Hello,
I'm a little confused about None in comparison.

 id ( None )
3086100672L
 id ( 1 )
134541104
 None  1
True


I thought, the id of the object is the last comparison criterion.
Therefore, None must be greater then 1.
Where is the behaviour of the comparison defined?. In the __cmp__ of
int. Or in the global cmp Function?

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


Re: interpreter vs. compiled

2008-07-18 Thread [EMAIL PROTECTED]
On Jul 18, 2:31 pm, castironpi [EMAIL PROTECTED] wrote:
 Given that, what does that column indicate?

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


Re: wholesale n i k e [...]

2008-07-18 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
 [incomplete babbling removed]

I guess this guy meant the whole snake, but messed up his keyboard.

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


Re: None in comparison

2008-07-18 Thread Marc 'BlackJack' Rintsch
On Thu, 17 Jul 2008 23:52:13 -0700, r.grimm wrote:

 Hello,
 I'm a little confused about None in comparison.
 
 id ( None )
 3086100672L
 id ( 1 )
 134541104
 None  1
 True

 
 I thought, the id of the object is the last comparison criterion.

Obviously that expectation is false.  The result of a comparison between
different types, with no `__cmp__()` method that says otherwise, is a
arbitrarily but consistent ordering by type.  The language doesn't even
guarantee that it must be consistent in different runs of the same program
in the same interpreter, just within one run.

So if you plan to rely on such implementation details, your program is
broken.

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


Re: singletons

2008-07-18 Thread Paddy
On Jul 16, 11:20 pm, Craig Allen [EMAIL PROTECTED] wrote:
 Hey, forgive me for just diving in, but I have a question I was
 thinking of asking on another list but it really is a general question
 so let me ask it here.  It's about how to approach making singletons.

Hi Craig,
This might be good for a general background on Design Patters in
Python:

http://uk.youtube.com/watch?v=0vJJlVBVTFg

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


Re: About wmi

2008-07-18 Thread patrol
On 7月17日, 下午4时22分, Tim Golden [EMAIL PROTECTED] wrote:
 patrol wrote:
  I will try to modify the wmi.py ,however I'm a novice.It will take a
  long time. You can give it up temporarily. If you don't mind ,can you
  tell me where needs modifying and how? Just unicode? Or Other?

 OK. Thanks for your patience on this one, Patrol. What I propose
 to do is to dig into the pywin32 sources to determine what's going
 on when the error messages are fetched. Then I'll be better placed
 to decide what to do when they come out. On the surface, the current
 module should be handling things correctly; but I've obviously missed
 an encode/decode somewhere.

 If I can think of an (even hackish) workaround for you in the meantime,
 I'll let you know. Until then...

 TJG

Thanks for Tim's help.

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

sub typing built in type with common attributes. Am I right?

2008-07-18 Thread King
I am new to python and getting into classes. Here I am trying to
create subtype of built in types with some additional attributes and
function. 'Attributes' is the main class and holds all the common
attributes that requires by these subtypes. This is what I came out
with. I need to know whether everything is right here ? or there are
some  better ways to do it.

class Attribute(object):

Common attributes and methods for custom types


def __init__(self, name=None, type=None, range=None, label=None):

#read only attributes
self._name = name
self._type = type
self._range = range

#read/write attribute
self.label = label

#make read only attributes
name = property(lambda self: self._name)
type = property(lambda self: self._type)
range = property(lambda self: self._range)

class Float(float, Attribute):

'''Custom Float class with some additional attributes.'''

__slots__ = ['_Attribute__name', '_Attribute__type',
'_Attribute__range', 'label']

def __new__(cls, value=0.0, *args, **kwargs):
return float.__new__(cls, value)

def __init__(self, value=0.0, name=None, label=None, type=None,
range=(0.0, 1.0)):
super(Float, self).__init__(name=name, label=label, type=type,
range=range)

def __str__(self):
return '{ %s }' % (float.__str__(self))

class Int(int, Attribute):

'''Custom Int class with some additional attributes.'''

__slots__ = ['_Attribute__name', '_Attribute__type',
'_Attribute__range', 'label']

def __new__(cls, value=0.0, *args, **kwargs):
return int.__new__(cls, value)

def __init__(self, value=0.0, name=None, label=None, type=None,
range=(0.0, 1.0)):
super(Int, self).__init__(name=name, label=label, type=type,
range=range)

def __str__(self):
return '{ %s }' % (int.__str__(self))
--
http://mail.python.org/mailman/listinfo/python-list


Re: % sign in python?

2008-07-18 Thread Terry Reedy



Tim Roberts wrote:

Steven Howe [EMAIL PROTECTED] wrote:


Terry Reedy wrote:

korean_dave wrote:

What does this operator do? Specifically in this context

test.log( [[Log level %d: %s]] % ( level, msg ), description )

I thought, in this contexted, it was  mapping operator.


You miss clipped. I never wrote that.  Please be careful, especially 
about attributing mis-information.



What??

Python does not have a mapping operator.  It has a map function, but no
equivalent operator.

% is either the string formatting operator (when the left-hand operand is a
string) or the modulo operator (when the left-hand operand is a number).


Which I learned 10 years ago.  What I did write was a pre-announcement 
of a Python symbol glossary, which I just finished a first draft of. 
And now to bed ;-)


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


Re: None in comparison

2008-07-18 Thread Terry Reedy



Marc 'BlackJack' Rintsch wrote:

On Thu, 17 Jul 2008 23:52:13 -0700, r.grimm wrote:


Hello,
I'm a little confused about None in comparison.


id ( None )

3086100672L

id ( 1 )

134541104

None  1

True
I thought, the id of the object is the last comparison criterion.


Obviously that expectation is false.  The result of a comparison between
different types, with no `__cmp__()` method that says otherwise, is a
arbitrarily but consistent ordering by type.  The language doesn't even
guarantee that it must be consistent in different runs of the same program
in the same interpreter, just within one run.

So if you plan to rely on such implementation details, your program is
broken.


And in 3.0 such arbitrary comparisons are gone.
 None  1
Traceback (most recent call last):
  File pyshell#8, line 1, in module
None  1
TypeError: unorderable types: NoneType()  int()

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


Re: Python Behind a Squid Corporate Proxy on Windows

2008-07-18 Thread Chris
On Jul 17, 6:40 pm, Larry Hale [EMAIL PROTECTED] wrote:
 Err, the line above should be:

 proxy_handler = urllib2.ProxyHandler( { http: http://
 myusername:[EMAIL PROTECTED]:3128 } )

 (Sorry!  :)

some old code I wrote to download public domain info for our company,
also through a squid proxy and this still works for me

import urllib2, urllib

proxy = urllib2.ProxyHandler({'http': 'http://
username:[EMAIL PROTECTED]:proxy_port'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)

conn = urllib2.urlopen('http://python.org')
return_str = conn.read()

fp = open('python.html','w').write(return_str)
--
http://mail.python.org/mailman/listinfo/python-list


Question on Joining of list

2008-07-18 Thread SUBHABRATA
Dear Group,
I am trying the following code line:
def try2(n):
a1=raw_input(PRINT A STRING:)
a2=a1.split()
a3=God Godess Heaven Sky
for x in a2:
a4=a3.find(x)
if a4-1:
a5=a3[a4]
print a5
elif a40:
a6=x
print It is not found
print a6
else:
print Error
s=a5+ +a6
print s

Here, if I put a string like:
Petrol Helium Heaven Sky
In s it is giving me S Helium
But I am looking for an output of  a5 and a6 concatenating all its
values not the last ones. Can you suggest me any help? Am I missing
any minor point?
Best Regards,
Subhabrata.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected default arguments behaviour (Maybe bug?)

2008-07-18 Thread sukkopera
FYI, I have opened a bug on the official tracker: 
http://bugs.python.org/issue3403.
--
http://mail.python.org/mailman/listinfo/python-list


checking if an object IS in a list

2008-07-18 Thread nicolas . pourcelot
Hi,

I want to test if an object IS in a list (identity and not equality
test).
I can if course write something like this :

test = False
myobject = MyCustomClass(*args, **kw)
for element in mylist:
if element is myobject:
test = True
break

and I can even write a isinlist(elt, mylist) function.

But most of the time, when I need some basic feature in python, I
discover later it is in fact already implemented. ;-)

So, is there already something like that in python ?
I tried to write :
'element is in mylist'
but this appeared to be incorrect syntax...

All objects involved all have an '__eq__' method.


Thanks,

N. P.

PS: Btw, how is set element comparison implemented ? My first
impression was that 'a' and 'b' members are considered equal if and
only if hash(a) == hash(b), but I was obviously wrong :
 class A(object):
... def __eq__(self,y):
... return False
... def __hash__(self):
... return 5
...
 a=A();b=A()
 a==b
False
 hash(b)==hash(a)
True
 b in set([a])
False
 S=set([a])
 S.difference([b])
set([__main__.A object at 0xb7a91dac])

So there is some equality check also, maybe only if '__eq__' is
implemented ?
--
http://mail.python.org/mailman/listinfo/python-list


Glamour models Fasion designing New look watch my profile http://www.geocities.com/cathrina39

2008-07-18 Thread hot rathi
Glamour models  Fasion designing
New look

watch my profile


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


Re: sub typing built in type with common attributes. Am I right?

2008-07-18 Thread Peter Otten
King wrote:

 I am new to python and getting into classes. Here I am trying to
 create subtype of built in types with some additional attributes and
 function. 'Attributes' is the main class and holds all the common
 attributes that requires by these subtypes. This is what I came out
 with. I need to know whether everything is right here ? or there are
 some  better ways to do it.

There may be some technical errors in your code, e. g. 

- the __slots__ look like a bit of bullshit: you already have a __dict__
  from the Attribute base class
- name mangling is done for attributes starting with two underscores

But the greater problem I see is that you are building up a huge bureaucracy
where pythonic code would concentrate on a concrete goal with minimal
administrative overhead.

Peter

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


Re: checking if an object IS in a list

2008-07-18 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 Hi,
 
 I want to test if an object IS in a list (identity and not equality
 test).
 I can if course write something like this :
 
 test = False
 myobject = MyCustomClass(*args, **kw)
 for element in mylist:
 if element is myobject:
 test = True
 break
 
 and I can even write a isinlist(elt, mylist) function.
 
 But most of the time, when I need some basic feature in python, I
 discover later it is in fact already implemented. ;-)
 
 So, is there already something like that in python ?
 I tried to write :
 'element is in mylist'
 but this appeared to be incorrect syntax...

There is no is in operator in Python, but you can write your test more
concisely as

any(myobject is element for element in mylist)


 PS: Btw, how is set element comparison implemented ? My first
 impression was that 'a' and 'b' members are considered equal if and
 only if hash(a) == hash(b), but I was obviously wrong :
 class A(object):
 ... def __eq__(self,y):
 ...   return False
 ... def __hash__(self):
 ...   return 5
 ...
 a=A();b=A()
 a==b
 False
 hash(b)==hash(a)
 True
 b in set([a])
 False
 S=set([a])
 S.difference([b])
 set([__main__.A object at 0xb7a91dac])
 
 So there is some equality check also, maybe only if '__eq__' is
 implemented ?

In general equality is determined by __eq__() or __cmp__(). By default
object equality checks for identity.

Some containers (like the built-in set and dict) assume that a==b implies
hash(a) == hash(b).

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


Re: sub typing built in type with common attributes. Am I right?

2008-07-18 Thread King
My mistake...
The correct __slots__ is like:
__slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range',
'label']

Could you please suggest an alternative or code improvement for the
matter.

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


Re: Question on Joining of list

2008-07-18 Thread Marc 'BlackJack' Rintsch
On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote:

 def try2(n):
   a1=raw_input(PRINT A STRING:)
   a2=a1.split()
   a3=God Godess Heaven Sky
   for x in a2:
   a4=a3.find(x)
   if a4-1:
   a5=a3[a4]
   print a5
   elif a40:
   a6=x
   print It is not found
   print a6
   else:
   print Error
   s=a5+ +a6
   print s
 
 Here, if I put a string like:
 Petrol Helium Heaven Sky
 In s it is giving me S Helium
 But I am looking for an output of  a5 and a6 concatenating all its
 values not the last ones. Can you suggest me any help? Am I missing
 any minor point?

Maybe you should describe what the input looks like and what output you
want to have and how the input and output are connected.  In words, not in
not very clear code with numbered names.  That's a silly idea and makes
understanding the code very hard.  Please use meaningful names!

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


Re: % sign in python?

2008-07-18 Thread Ken Starks

Terry Reedy wrote:



korean_dave wrote:

What does this operator do? Specifically in this context

test.log( [[Log level %d: %s]] % ( level, msg ), description )

(Tried googling and searching, but the % gets interpreted as an
operation and distorts the search results)


Having seen a number of comments like this over the years (about the 
difficulty of searching for symbol meanings), I just started, last 
night, a symbol index listing nearly all Python syntax uses of 
non-alpha-or-digit ascii symbols.  When I finish and upload it 
somewhere, I will post an announcement with the link.


tjr



This will be excellent, Terry.

For the present case, perhaps we should also point out that in
python 3.0:

 Note

The formatting operations described here are obsolete and may go away in 
   future versions of Python. Use the new String Formatting in new code.


(Taken from the provisional documentation at:

http://docs.python.org/dev/3.0/library/stdtypes.html#old-string-formatting
)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Joining of list

2008-07-18 Thread Peter Otten
SUBHABRATA wrote:

 I am trying the following code line:

def try2(n):
user_line = raw_input(PRINT A STRING:)
user_words = user_line.split()
my_line = God Godess Heaven Sky
for word in user_words:
pos = my_line.find(word)
if pos - 1:
first_char = my_line[pos]
print first_char
elif pos  0:
missing_word = word
print It is not found
print missing_word
else:
print Error
s = first_char +   + missing_word
print s

try2(1)

Do you recognise your code? With that jumpstart you should find the error in
no time ;)

 Here, if I put a string like:
 Petrol Helium Heaven Sky
 In s it is giving me S Helium
 But I am looking for an output of  a5 and a6 concatenating all its
 values not the last ones. Can you suggest me any help? Am I missing
 any minor point?

Yes, use meaningful variables. They won't make your code magically correct
but will make it a lot easier to pinpoint mistakes and false assumptions --
for you and others.

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


Re: Question on Joining of list

2008-07-18 Thread SUBHABRATA
Sorry if I didn't say that.
The input is a string Petrol Helium Heaven Sky
Now, in a3 it is God Goddess Heaven Sky is there,
it is matching Heaven and Sky but not Petrol and Helium as they are
not in a3.
Now, as per the code it is giving me an output S of Sky and
Helium
But I was looking for an output of  H S Petrol Helium and not S
Helium meaning all the values of a5 and a6 will be concatenated in s.
Best Regards,
Subhabrata..

Marc 'BlackJack' Rintsch wrote:
 On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote:

  def try2(n):
  a1=raw_input(PRINT A STRING:)
  a2=a1.split()
  a3=God Godess Heaven Sky
  for x in a2:
  a4=a3.find(x)
  if a4-1:
  a5=a3[a4]
  print a5
  elif a40:
  a6=x
  print It is not found
  print a6
  else:
  print Error
  s=a5+ +a6
  print s
 
  Here, if I put a string like:
  Petrol Helium Heaven Sky
  In s it is giving me S Helium
  But I am looking for an output of  a5 and a6 concatenating all its
  values not the last ones. Can you suggest me any help? Am I missing
  any minor point?

 Maybe you should describe what the input looks like and what output you
 want to have and how the input and output are connected.  In words, not in
 not very clear code with numbered names.  That's a silly idea and makes
 understanding the code very hard.  Please use meaningful names!

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


Re: checking if an object IS in a list

2008-07-18 Thread nicolas . pourcelot
On 18 juil, 11:30, Peter Otten [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  Hi,

  I want to test if an object IS in a list (identity and not equality
  test).
  I can if course write something like this :

  test = False
  myobject = MyCustomClass(*args, **kw)
  for element in mylist:
      if element is myobject:
          test = True
          break

  and I can even write a isinlist(elt, mylist) function.

  But most of the time, when I need some basic feature in python, I
  discover later it is in fact already implemented. ;-)

  So, is there already something like that in python ?
  I tried to write :
  'element is in mylist'
  but this appeared to be incorrect syntax...

 There is no is in operator in Python, but you can write your test more
 concisely as

 any(myobject is element for element in mylist)




Thanks a lot
However, any() is only available if python version is = 2.5, but I
may define a any() function on initialisation, if python version  2.5

I think something like
 id(myobject) in (id(element) for element in mylist)
would also work, also it's not so readable, and maybe not so fast
(?)...

An is in operator would be nice...

  PS: Btw, how is set element comparison implemented ? My first
  impression was that 'a' and 'b' members are considered equal if and
  only if hash(a) == hash(b), but I was obviously wrong :
  class A(object):
  ... def __eq__(self,y):
  ...   return False
  ... def __hash__(self):
  ...   return 5
  ...
  a=A();b=A()
  a==b
  False
  hash(b)==hash(a)
  True
  b in set([a])
  False
  S=set([a])
  S.difference([b])
  set([__main__.A object at 0xb7a91dac])

  So there is some equality check also, maybe only if '__eq__' is
  implemented ?

 In general equality is determined by __eq__() or __cmp__(). By default
 object equality checks for identity.

 Some containers (like the built-in set and dict) assume that a==b implies
 hash(a) == hash(b).

 Peter

So, precisely, you mean that if hash(a) != hash(b), a and b are
considered distinct, and else [ie. if hash(a) == hash(b)], a and b are
the same if and only if a == b ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Joining of list

2008-07-18 Thread SUBHABRATA
Thanx Peter,
I would change my variables next time I would post. And obviously,
thanx for your solution. I am reviewing it, I was also trying out some
solutions.
Best Regards,
Subhabrata.

Peter Otten wrote:
 SUBHABRATA wrote:

  I am trying the following code line:

 def try2(n):
 user_line = raw_input(PRINT A STRING:)
 user_words = user_line.split()
 my_line = God Godess Heaven Sky
 for word in user_words:
 pos = my_line.find(word)
 if pos - 1:
 first_char = my_line[pos]
 print first_char
 elif pos  0:
 missing_word = word
 print It is not found
 print missing_word
 else:
 print Error
 s = first_char +   + missing_word
 print s

 try2(1)

 Do you recognise your code? With that jumpstart you should find the error in
 no time ;)

  Here, if I put a string like:
  Petrol Helium Heaven Sky
  In s it is giving me S Helium
  But I am looking for an output of  a5 and a6 concatenating all its
  values not the last ones. Can you suggest me any help? Am I missing
  any minor point?

 Yes, use meaningful variables. They won't make your code magically correct
 but will make it a lot easier to pinpoint mistakes and false assumptions --
 for you and others.

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


Re: sub typing built in type with common attributes. Am I right?

2008-07-18 Thread Peter Otten
King wrote:

 My mistake...
 The correct __slots__ is like:
 __slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range',
 'label']
 
 Could you please suggest an alternative or code improvement for the
 matter.

How about 

class AttributesMixin(object):
Warning: If you change name, type, or range of an existing object
   your computer will explode and you will have noone else to blame.

def __init__(self, name=None, type=None, range=None, label=None):
self.name = name
self.type = type
self.range = range
self.label = label

class Float(float, AttributesMixin): pass
class Int(int, AttributesMixin): pass

Now go and write something useful :-)

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


Protecting instance variables

2008-07-18 Thread Nikolaus Rath
Hello,

I am really surprised that I am asking this question on the mailing
list, but I really couldn't find it on python.org/doc.

Why is there no proper way to protect an instance variable from access
in derived classes?

I can perfectly understand the philosophy behind not protecting them
from access in external code (protection by convention), but isn't
it a major design flaw that when designing a derived class I first
have to study the base classes source code? Otherwise I may always
accidentally overwrite an instance variable used by the base class...


Best,

   -Nikolaus

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

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C

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

Re: Unusual Exception Behaviour

2008-07-18 Thread mk

Ok, Just to add a little interest, when I comment out the configuration line
for my logging, like so:

#logging.config.fileConfig(/myapp/configuration/logging.conf)




It appears to throw the exceptions as normal :-) :-s


To tell the truth I have never used logging module extensively, so I'm 
not expert in this area and can't help you there.


However, it seems to me that you may have stumbled upon some subtle bug 
/ side effect of logging module that could cause some side effects in 
exceptions. Or perhaps it surfaces only in combination with glib?


If you discover the root cause, please let us know on this ng, I'm also 
using Python extensions and bindings to other libraries and this could 
be of interest at least to me.






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


Re: Question on Joining of list

2008-07-18 Thread SUBHABRATA
Hi Peter,
In your code s would print first_char(of the last word)+
+missing_word(the last word) I was looking all.
Best Regards,
Subhabrata.

SUBHABRATA wrote:
 Sorry if I didn't say that.
 The input is a string Petrol Helium Heaven Sky
 Now, in a3 it is God Goddess Heaven Sky is there,
 it is matching Heaven and Sky but not Petrol and Helium as they are
 not in a3.
 Now, as per the code it is giving me an output S of Sky and
 Helium
 But I was looking for an output of  H S Petrol Helium and not S
 Helium meaning all the values of a5 and a6 will be concatenated in s.
 Best Regards,
 Subhabrata..

 Marc 'BlackJack' Rintsch wrote:
  On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote:
 
   def try2(n):
 a1=raw_input(PRINT A STRING:)
 a2=a1.split()
 a3=God Godess Heaven Sky
 for x in a2:
 a4=a3.find(x)
 if a4-1:
 a5=a3[a4]
 print a5
 elif a40:
 a6=x
 print It is not found
 print a6
 else:
 print Error
 s=a5+ +a6
 print s
  
   Here, if I put a string like:
   Petrol Helium Heaven Sky
   In s it is giving me S Helium
   But I am looking for an output of  a5 and a6 concatenating all its
   values not the last ones. Can you suggest me any help? Am I missing
   any minor point?
 
  Maybe you should describe what the input looks like and what output you
  want to have and how the input and output are connected.  In words, not in
  not very clear code with numbered names.  That's a silly idea and makes
  understanding the code very hard.  Please use meaningful names!
 
  Ciao,
  Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Joining of list

2008-07-18 Thread Peter Otten
SUBHABRATA wrote:

 Thanx Peter,
 I would change my variables next time I would post. 

No, you should use meaningful variable names when you write your code no
matter whether you plan to post it or not.

 And obviously, 
 thanx for your solution. I am reviewing it, I was also trying out some
 solutions.

You misunderstood. I did not modify your code other than changing the
variable names. My hope was that with this modification any errors sprang
to you eye...

Peter


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


Re: Best Python packages?

2008-07-18 Thread Ben Sizer
On Jul 16, 3:31 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Ben Sizer wrote:
  make my development a lot easier.

 Knowing what kind of development you do might help, of course.  Some
 libraries are excellent in some contexts and suck badly in others...

Sure. Mostly I'm just interested in what's out there though. In C++
you have Boost which everybody knows are a source of high quality
libraries, covering a fairly wide set of applications. Obviously
that's more low-level and less application specific, and the Python
standard libs do pretty much everything that is in Boost, but it's
that sort of peer-reviewed and widely-applicable list that I'd like to
see.

I (attempt to) use TurboGears for web development and that depends on
a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch,
SimpleJson, FormEncode, etc - and I would never have heard of these if
TurboGears' exposure of its internals wasn't so common. Some of these
are web-specific but some are not. And I'd never know to look for them
specificially, because in many cases it wouldn't occur to me that they
exist. (eg. Object-Relational Mappers like SQLObject may be obvious if
you come from certain areas of IT, but I'd never heard of them before
I started with TurboGears.)

For what it's worth, my main areas of interest are gaming, multimedia,
and web development. But I just like to hear about anything that
people might use which makes their life a lot easier and which perhaps
is not application specific - like ORMs or something similar.

 Looking at things that larger projects and distributions use can also be
 a good idea.  For example, if you're doing scientific stuff, go directly
 to enthought.com.  If you're doing web stuff, look at the libraries big
 Django applications use.  Etc.

Sadly, I know just as little about what major applications are out
there as I do about what libraries are out there!

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


Re: sub typing built in type with common attributes. Am I right?

2008-07-18 Thread Maric Michaud
Le Friday 18 July 2008 11:36:20 King, vous avez écrit :
 Could you please suggest an alternative or code improvement for the
 matter.

I'm not sure what you are trying to achieve with your snippet, but I suspect 
it's some sort of templating, right ? If so, using the dynamic nature of 
python should help :

[103]: def make_subtype_with_attr(type_, ro_attr, rw_attr) :
dic = {}
for i in ro_attr : dic[i] = property(lambda s, n=i : getattr(s, '_'+n))
def __new__(cls, *args, **kwargs) :
instance = type_.__new__(cls, *args)
for i in rw_attr : setattr(instance, i, kwargs[i])
for i in ro_attr : setattr(instance, '_'+i, ro_attr[i])
return instance
dic['__new__'] = __new__
return type('my_' + type_.__name__, (type_,), dic)
   .:

[113]: my_int = make_subtype_with_attr(int, 
{'name' : 'myint', 'id':123452}, ('foo',))

[114]: i = my_int(5, foo=3)

[115]: i.foo
...[115]: 3

[116]: i
...[116]: 5

[117]: i.id
...[117]: 123452

[118]: i.id = 2
---
AttributeErrorTraceback (most recent call last)

/home/maric/ipython console in module()

AttributeError: can't set attribute


-- 
_

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


Re: checking if an object IS in a list

2008-07-18 Thread nicolas . pourcelot
In fact, 'any(myobject is element for element in mylist)' is 2 times
slower than using a for loop, and 'id(myobject) in (id(element) for
element in mylist)' is 2.4 times slower.

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


Re: checking if an object IS in a list

2008-07-18 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 I think something like
 id(myobject) in (id(element) for element in mylist)
 would also work, also it's not so readable, and maybe not so fast
 (?)...
 
 An is in operator would be nice...

And rarely used. Probably even less than the (also missing)

 in, | in, you-name-it 

operators...

 So, precisely, you mean that if hash(a) != hash(b), a and b are
 considered distinct, and else [ie. if hash(a) == hash(b)], a and b are
 the same if and only if a == b ?

Correct for set, dict. For lists etc. the hash doesn't matter:

 class A(object):
... def __hash__(self):
... return nexthash()
... def __eq__(self, other):
... return True
...
 from itertools import count
 nexthash = count().next
 A() in [A() for _ in range(3)]
True
 d = dict.fromkeys([A() for a in range(3)])
 d.keys()[0] in d
False

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


trying to match a string

2008-07-18 Thread arnimavidyarthy
Hi,

Hi,

I am taking a string as an input from the user and it should only
contain the chars:L , M or R

I tried the folllowing in kodos but they are still not perfect:

[^A-K,^N-Q,^S-Z,^0-9]
[L][M][R]
[LRM]?L?[LRM]? etc but they do not exactly meet what I need.

For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

regards,
SZ

The string may or may not have all the three chars.
--
http://mail.python.org/mailman/listinfo/python-list


trying to match a string

2008-07-18 Thread arnimavidyarthy
Hi,

Hi,

I am taking a string as an input from the user and it should only
contain the chars:L , M or R

I tried the folllowing in kodos but they are still not perfect:

[^A-K,^N-Q,^S-Z,^0-9]
[L][M][R]
[LRM]?L?[LRM]? etc but they do not exactly meet what I need.

For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

regards,
SZ

The string may or may not have all the three chars.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Protecting instance variables

2008-07-18 Thread Diez B. Roggisch

Nikolaus Rath schrieb:

Hello,

I am really surprised that I am asking this question on the mailing
list, but I really couldn't find it on python.org/doc.

Why is there no proper way to protect an instance variable from access
in derived classes?

I can perfectly understand the philosophy behind not protecting them
from access in external code (protection by convention), but isn't
it a major design flaw that when designing a derived class I first
have to study the base classes source code? Otherwise I may always
accidentally overwrite an instance variable used by the base class...



Here we go again...

http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/

To directly answer your question: that's what the __ (double underscore) 
name mangling is for.


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


Re: Question on Joining of list

2008-07-18 Thread SUBHABRATA
Hi Peter,
Peter Otten wrote:
 SUBHABRATA wrote:

  Thanx Peter,
  I would change my variables next time I would post.

 No, you should use meaningful variable names when you write your code no
 matter whether you plan to post it or not.
Good You are teaching me something good in life. Thanx.

  And obviously,
  thanx for your solution. I am reviewing it, I was also trying out some
  solutions.

 You misunderstood. I did not modify your code other than changing the
 variable names. My hope was that with this modification any errors sprang
 to you eye...
I was seeing that.
I am almost near the solution. You can also try some hands if you
feel.
Best Regards,
Subhabrata.

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


Re: trying to match a string

2008-07-18 Thread Eddie Corns
[EMAIL PROTECTED] writes:

Hi,

Hi,

I am taking a string as an input from the user and it should only
contain the chars:L , M or R

I tried the folllowing in kodos but they are still not perfect:

[^A-K,^N-Q,^S-Z,^0-9]
[L][M][R]
[LRM]?L?[LRM]? etc but they do not exactly meet what I need.

For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

regards,
SZ

The string may or may not have all the three chars.


 var = 'LRLRLRNL'
 residue = var.replace('L','').replace('R','').replace('M','')
 if residue != '':
...   print 'Invalid characters in input',residue
... 
Invalid characters in input N
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Joining of list

2008-07-18 Thread Quentin Gallet-Gilles
Actually, since you want to keep the missing words apart from the found
ones, it's not necessary to do that. Using first_char and missing_word
(quoting Peter's code) as lists instead of strings comes to mind, then you
can join both lists into a string once the code exits the for loop.

Cheers,
Quentin

On Fri, Jul 18, 2008 at 12:34 PM, Subhabrata Banerjee 
[EMAIL PROTECTED] wrote:

  Dear Quentin,
 That's true but where to place, if I use it after elif it is not giving
 result but if I give in after for there is no use of iteration.
 I'm thinking to use a3.find(s) whichever not availiable to split and
 iterate and join with s.
 Best Regards,
 Subhabrata.


 --

 Date: Fri, 18 Jul 2008 12:11:00 +0200
 From: [EMAIL PROTECTED]
 To: [EMAIL PROTECTED]
 Subject: Re: Question on Joining of list



 In that case, the line 's=a5+ +a6' should be inside the for loop (and
 slightly modified to concatenate the results)

 Cheers,
 Quentin

 On Fri, Jul 18, 2008 at 12:00 PM, SUBHABRATA [EMAIL PROTECTED]
 wrote:

 Sorry if I didn't say that.
 The input is a string Petrol Helium Heaven Sky
 Now, in a3 it is God Goddess Heaven Sky is there,
 it is matching Heaven and Sky but not Petrol and Helium as they are
 not in a3.
 Now, as per the code it is giving me an output S of Sky and
 Helium
 But I was looking for an output of  H S Petrol Helium and not S
 Helium meaning all the values of a5 and a6 will be concatenated in s.
 Best Regards,
 Subhabrata..

 Marc 'BlackJack' Rintsch wrote:
  On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote:
 
   def try2(n):
   a1=raw_input(PRINT A STRING:)
   a2=a1.split()
   a3=God Godess Heaven Sky
   for x in a2:
   a4=a3.find(x)
   if a4-1:
   a5=a3[a4]
   print a5
   elif a40:
   a6=x
   print It is not found
   print a6
   else:
   print Error
   s=a5+ +a6
   print s
  
   Here, if I put a string like:
   Petrol Helium Heaven Sky
   In s it is giving me S Helium
   But I am looking for an output of  a5 and a6 concatenating all its
   values not the last ones. Can you suggest me any help? Am I missing
   any minor point?
 
  Maybe you should describe what the input looks like and what output you
  want to have and how the input and output are connected.  In words, not
 in
  not very clear code with numbered names.  That's a silly idea and makes
  understanding the code very hard.  Please use meaningful names!
 
  Ciao,
Marc 'BlackJack' Rintsch
 --
 http://mail.python.org/mailman/listinfo/python-list



 --
 This is your window into tinsel town. Keep abreast with the latest movie
 releases, star shockers and juicy gossip. Try 
 it!http://entertainment.in.msn.com/

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

Re: sub typing built in type with common attributes. Am I right?

2008-07-18 Thread King
Thanks Michaud,

You have actually solved an another problem by
'make_subtype_with_attr' function.

What actually I am trying to do here is to create custom types using
built in types to use in my application.
For example , float2, float3, color, vector, point, normal, matrix
etc. The reason being creating as individual subtypes is because each
subtypes has it's own set of functions as well as common functions and
attributes defined in 'Attribute' class.

Although I won't be doing any math using subtypes like multiply a
color by another color or add a float and a color. One of the
important function that every subtype has is to print itself in a
special format. For 'color' it would be :

'type' + 'name' + ' = color('+color[0]+', '+color[2]+',
'+color[2]+');'
Result: color myColor = color(0.5, 0.1, 1.0);

I hope this will make things more clearer. If you do have any
suggestions then please send it across.

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


RE: Unusual Exception Behaviour

2008-07-18 Thread Robert Rawlins
Hi Mk,

 To tell the truth I have never used logging module extensively, so I'm 
 not expert in this area and can't help you there.

 However, it seems to me that you may have stumbled upon some subtle bug 
 / side effect of logging module that could cause some side effects in 
 exceptions. Or perhaps it surfaces only in combination with glib?

 If you discover the root cause, please let us know on this ng, I'm also 
 using Python extensions and bindings to other libraries and this could 
 be of interest at least to me.

Yeah it's got me a little bemused to be honest, I've tried playing around
with configuration options this morning and not been able to achieve
anything that works properly.

I'll keep testing though and as soon as I have a root cause to the problem
I'll be sure to let the list know.

Thanks mate,

Robert

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


welcome to $500 monthly in onlin jobs jest join him with in all datting in girls frined available

2008-07-18 Thread hot
welcome to $500 monthly in onlin jobs jest join  him with in all
datting  in girls frined  available
in all information viset
welcome to $500 monthly in onlin jobs jest join  him with in all
datting  in girls frined  available
in all information viset  web

http://www.friendfinder.com/go/g775836-pmem
http://mountanbikes.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: trying to match a string

2008-07-18 Thread John Machin
On Jul 18, 8:33 pm, [EMAIL PROTECTED] wrote:
 Hi,

 Hi,

 I am taking a string as an input from the user and it should only
 contain the chars:L , M or R

 I tried the folllowing in kodos but they are still not perfect:

 [^A-K,^N-Q,^S-Z,^0-9]
 [L][M][R]
 [LRM]?L?[LRM]? etc but they do not exactly meet what I need.

 For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

 regards,
 SZ

 The string may or may not have all the three chars.

re.match(r'[LMR]+\Z', your_string)

in English: one or more of L, M , or R, followed by the end of the
string.
--
http://mail.python.org/mailman/listinfo/python-list


Re: trying to match a string

2008-07-18 Thread oj
On Jul 18, 11:33 am, [EMAIL PROTECTED] wrote:
 Hi,

 Hi,

 I am taking a string as an input from the user and it should only
 contain the chars:L , M or R

 I tried the folllowing in kodos but they are still not perfect:

 [^A-K,^N-Q,^S-Z,^0-9]
 [L][M][R]
 [LRM]?L?[LRM]? etc but they do not exactly meet what I need.

 For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

 regards,
 SZ

 The string may or may not have all the three chars.

With regular expressions, [^LRM] matches a character that isn't L, R
or M. So:

import re

var = LRLRLRLNR

if re.search(r'[^LRM]', var):
print Invalid
--
http://mail.python.org/mailman/listinfo/python-list


Re: trying to match a string

2008-07-18 Thread arni
On Jul 18, 3:46 pm, [EMAIL PROTECTED] (Eddie Corns) wrote:
 [EMAIL PROTECTED] writes:
 Hi,
 Hi,
 I am taking a string as an input from the user and it should only
 contain the chars:L , M or R
 I tried the folllowing in kodos but they are still not perfect:
 [^A-K,^N-Q,^S-Z,^0-9]
 [L][M][R]
 [LRM]?L?[LRM]? etc but they do not exactly meet what I need.
 For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.
 regards,
 SZ
 The string may or may not have all the three chars.
  var     = 'LRLRLRNL'
  residue = var.replace('L','').replace('R','').replace('M','')
  if residue != '':

 ...   print 'Invalid characters in input',residue
 ...
 Invalid characters in input N

That was quick.Thanks.Never thought it that angle :(
--
http://mail.python.org/mailman/listinfo/python-list


Re: trying to match a string

2008-07-18 Thread John Machin
On Jul 18, 9:05 pm, oj [EMAIL PROTECTED] wrote:
 On Jul 18, 11:33 am, [EMAIL PROTECTED] wrote:



  Hi,

  Hi,

  I am taking a string as an input from the user and it should only
  contain the chars:L , M or R

  I tried the folllowing in kodos but they are still not perfect:

  [^A-K,^N-Q,^S-Z,^0-9]
  [L][M][R]
  [LRM]?L?[LRM]? etc but they do not exactly meet what I need.

  For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

  regards,
  SZ

  The string may or may not have all the three chars.

 With regular expressions, [^LRM] matches a character that isn't L, R
 or M. So:

 import re

 var = LRLRLRLNR

 if re.search(r'[^LRM]', var):
 print Invalid

Fails if var refers to the empty string.
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if an object IS in a list

2008-07-18 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 In fact, 'any(myobject is element for element in mylist)' is 2 times
 slower than using a for loop, and 'id(myobject) in (id(element) for
 element in mylist)' is 2.4 times slower.
 
This is not a meaningful statement unless you at least qualify with the
number of item that are actually checked. For sufficently long sequences
both any() and the for loop take roughly the same amount of time over here.

$ python -m timeit -sitems=range(1000); x = 1000 any(x is item for item
in items)
1000 loops, best of 3: 249 usec per loop
$ python -m timeit -sitems=range(1000); x = 1000 for item in items:  
if x is item: break
1000 loops, best of 3: 276 usec per loop

$ python -m timeit -sitems=range(1000); x = 0 any(x is item for item in
items)
10 loops, best of 3: 3 usec per loop
$ python -m timeit -sitems=range(1000); x = 0 for item in items:   if x
is item: break
100 loops, best of 3: 0.317 usec per loop


Peter

PS: Take these numbers with a grain of salt, they vary a lot between runs.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected default arguments behaviour (Maybe bug?)

2008-07-18 Thread Sebastian lunar Wiesner
[EMAIL PROTECTED] [EMAIL PROTECTED]:

 On 13 Lug, 19:42, [EMAIL PROTECTED] wrote:
 I expect it's because default values for parameters are evaluated and
 bound at definition time. So once def m (self, param = a): line
 executes, the default value for parameter is forever bound to be 1.
 What you can do is for example:
 
 Yes, that's what I thought, too. Although, it does not seem to me the
 correct thing that has to be done, that is why I reported it.

It _is_ the correct thing.  Evaluation of default parameters at declaration
time and not at invocation is truely a language feature, not a bug.

You'll find your bug report being closed quickly.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if an object IS in a list

2008-07-18 Thread nicolas . pourcelot
On 18 juil, 12:26, Peter Otten [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  I think something like
  id(myobject) in (id(element) for element in mylist)
  would also work, also it's not so readable, and maybe not so fast
  (?)...

  An is in operator would be nice...

 And rarely used. Probably even less than the (also missing)

  in, | in, you-name-it

 operators...


Maybe, but imho
 myobject is in mylist
is highly readable, when
 myobject  in mylist
is not.
--
http://mail.python.org/mailman/listinfo/python-list


How to register an extension DLL with python 2.5?

2008-07-18 Thread Boaz Feldbaum
Hello all,

I wrote an extension dll in C++ using VS2005 to be used in windows platform. 
In pyhon 2.4 I used to copy my dll to the dlls sub-directory of python 
installation and import my dll and it worked fine. This doesn't work with 
python 2.5. I get the following when trying to import my dll:

 import pywutil
Traceback (most recent call last):
  File stdin, line 1, in module
ImportError: No module named pywutil


What should I do in 2.5 to be able to import my extension dll?

Thanks a lot in advance,
Boaz. 


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


Re: checking if an object IS in a list

2008-07-18 Thread nicolas . pourcelot
On 18 juil, 13:13, Peter Otten [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  In fact, 'any(myobject is element for element in mylist)' is 2 times
  slower than using a for loop, and 'id(myobject) in (id(element) for
  element in mylist)' is 2.4 times slower.

 This is not a meaningful statement unless you at least qualify with the
 number of item that are actually checked. For sufficently long sequences
 both any() and the for loop take roughly the same amount of time over here.


Sorry. I used short lists (a list of 20 floats) and the element
checked was not in the list.
(That was the case I usually deals with in my code.)
--
http://mail.python.org/mailman/listinfo/python-list


https in pylons

2008-07-18 Thread sniipe
Hello,

I have a question about framework pylons - how to run(in paster)
webpages over https? Is it possible, or not?

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


Re: Using Tcl extensions with Python?

2008-07-18 Thread Thomas Troeger

C Martin wrote:

How do you setup a Tcl extension to be accessible through Python? I
understand that I'll have to use native Tcl calls to use it (tk.call()
etc), but I can't figure out where to put the files or how to
initialize them so I can call them.

The package I would like to use is TkPNG: 
http://www.muonics.com/FreeStuff/TkPNG/

Thanks.


ARGH, Tcl!!! ;-) I know that's not the question, but do you know PIL 
(http://www.pythonware.com/products/pil)?

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


Re: storing references instead of copies in a dictionary

2008-07-18 Thread [EMAIL PROTECTED]
On 17 juil, 15:56, mk [EMAIL PROTECTED] wrote:
 Calvin Spealman wrote:
  To your actual problem... Why do you wanna do this anyway? If you want
  to change the function in the dictionary, why don't you simply define
  the functions you'll want to use, and change the one you have bound to
  the key in the dictionary when you want to change it? In other words,
  define them all at once, and then just d['1'] = new_f1. What is wrong
  with that?

 Well, basically nothing except I need to remember I have to do that.

 Suppose one does that frequently in a program. It becomes tedious. I
 think I will define some helper function then:

   def helper(fundict, newfun):
 ... fundict[newfun.func_name] = newfun
 ...

 _If_ there were some shorter and still proper way to do it, I'd use
 it.

You're halfway there.

from functools import partial

callbacks = {}
register_callback = partial(helper, callbacks)

@register_callback
def f1(arg):
print f1, arg

callbacks['f1']('ok')

@register_callback
def f1(arg):
print new f1, arg

callbacks['f1']('ok')

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


Re: How to process a very large (4Gb) tarfile from python?

2008-07-18 Thread Uwe Schmitt
Due to the discussion above I wrote a python module for scanning of
large tarfiles.
You can get it from http://www.procoders.net/wp-content/tarfile_scanner.zip

Greetings, Uwe

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


Re: trying to match a string

2008-07-18 Thread oj
On Jul 18, 12:10 pm, John Machin [EMAIL PROTECTED] wrote:
 On Jul 18, 9:05 pm, oj [EMAIL PROTECTED] wrote:



  On Jul 18, 11:33 am, [EMAIL PROTECTED] wrote:

   Hi,

   Hi,

   I am taking a string as an input from the user and it should only
   contain the chars:L , M or R

   I tried the folllowing in kodos but they are still not perfect:

   [^A-K,^N-Q,^S-Z,^0-9]
   [L][M][R]
   [LRM]?L?[LRM]? etc but they do not exactly meet what I need.

   For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

   regards,
   SZ

   The string may or may not have all the three chars.

  With regular expressions, [^LRM] matches a character that isn't L, R
  or M. So:

  import re

  var = LRLRLRLNR

  if re.search(r'[^LRM]', var):
      print Invalid

 Fails if var refers to the empty string.

No it doesn't, it succeeds if var is an empty string. An empty string
doesn't contain characters that are not L, R or M.

The OP doesn't specify whether an empty string is valid or not. My
interpretation was that an empty string would be valid.
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if an object IS in a list

2008-07-18 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 On 18 juil, 13:13, Peter Otten [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  In fact, 'any(myobject is element for element in mylist)' is 2 times
  slower than using a for loop, and 'id(myobject) in (id(element) for
  element in mylist)' is 2.4 times slower.

 This is not a meaningful statement unless you at least qualify with the
 number of item that are actually checked. For sufficently long sequences
 both any() and the for loop take roughly the same amount of time over
 here.

 
 Sorry. I used short lists (a list of 20 floats) and the element
 checked was not in the list.
 (That was the case I usually deals with in my code.)

What is your (concrete) use case, by the way?

If you want efficiency you should use a dictionary instead of the list
anyway:

$ python -m timeit -sd=dict((id(i), i) for i in range(1000)); x =
1000 id(x) in d
100 loops, best of 3: 0.275 usec per loop

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


substitution of list elements

2008-07-18 Thread antar2
I want to replace each first element in list 5 that is equal to the
first element of the list of lists4 by the fourth element. I wrote
following code that does not work:

list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q',
'f']]
list5 = ['1', '2', '3']

for j in list4:
  for k in list5:
if j[0] == k:
k = j[3]
print list5
Wanted result: ['c', 'e', '3']

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


Question regarding os.write() and write() method of a file descriptor

2008-07-18 Thread phil lemelin
Good Day python users,

I have a question regarding os.write and the write method of a file
descriptor object. My python was written on linux, under python 2.4 and I've
recently migrated to python 2.5.
My problem came from a pipe I used to to open and write to using :

fd = os.open(myfifo,w+)
os.write(fd,'some boring stuff\n')
os.close(fd)

I'm pretty sure that it worked on a previous version of python and linux
but, on my mandriva 2008, running python 2.5, I get the following exception
:

os.write(fd,'some boring stuff\n')
exceptions.TypeError: an integer is required


Now, I solved my problem by changing my code to the following :

fd open(myfifo,w+)
fd.write(some less boring stuff\n)
fd.close()


I still cant explain why it works with the file descriptor method and i'm
seeking an explanation.

Please, forgive me if it's a dumb question, but i'm just trying to get
better at python.

I hope someone will take time to help me out.
-- 
Philippe-Alexandre Lemelin
--
http://mail.python.org/mailman/listinfo/python-list

Re: checking if an object IS in a list

2008-07-18 Thread bearophileHUGS
Peter Otten:
 PS: Take these numbers with a grain of salt, they vary a lot between runs.

Another possibility :-)
from itertools import imap
id(x) in imap(id, items)


If you want efficiency you should use a dictionary instead of the list anyway:

I agree, but sometimes you have few items to look for, so building the
whole dict (that requires memory too) may be a waste of time.

In theory this may be faster to build, but in practice you need a
benchmark:
ids = set(imap(id, items))
followed by:
id(x) in ids

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: substitution of list elements

2008-07-18 Thread Wolfram Kraus

Am 18.07.2008 14:33, antar2 schrieb:

I want to replace each first element in list 5 that is equal to the
first element of the list of lists4 by the fourth element. I wrote
following code that does not work:

list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q',
'f']]
list5 = ['1', '2', '3']

for j in list4:
  for k in list5:

  for i,k in enumerate(list5):


if j[0] == k:
k = j[3]

  list5[i] = j[3]


print list5
Wanted result: ['c', 'e', '3']

thanks!


You didn't replace the list element itself.

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


Re: trying to match a string

2008-07-18 Thread Scott David Daniels

[EMAIL PROTECTED] wrote:

I am taking a string as an input from the user and it should only
contain the chars:L , M or R

How about skipping re's and doing something like:
   set(input_string) = set('LMR')
If you want to disallow the empty string:
   set([])  set(input_string) = set('LMR')

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected default arguments behaviour (Maybe bug?)

2008-07-18 Thread sukkopera
On 18 Lug, 13:23, Sebastian \lunar\ Wiesner
[EMAIL PROTECTED] wrote:
 It _is_ the correct thing.  Evaluation of default parameters at declaration
 time and not at invocation is truely a language feature, not a bug.

 You'll find your bug report being closed quickly.

It has ;). I had totally missed the tutorial section where it is
stated, which actually even has an example quite close to the one I
provided. Sorry for the waste of time.

Giorgio

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


Re: Problem with MySQLdb and mod_python

2008-07-18 Thread Graham Dumpleton
On Jul 18, 3:28 pm, John Nagle [EMAIL PROTECTED] wrote:
 Cyril Bazin wrote:
  Thanks for your reply

  The apache log contains lines like :

  [Tue Jul 15 23:31:01 2008] [notice]mod_python(pid=11836,
  interpreter='www.toto.fr'):Importing module
  '/usr/local/apache2/htdocs/intranet/courrier/test.py'
  [Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal
  Segmentation fault (11)
  [Tue Jul 15 23:31:19 2008] [notice]mod_python(pid=11764,
  interpreter='www.toto.fr'):Importing module
  '/usr/local/apache2/htdocs/intranet/courrier/test.py'
  [Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal
  Segmentation fault (11)

  I think the problem comes from the MySQLdb module.
  If I can't find another solution, I think I will downgrade the MySQLdb
  version to 1.2.1

     Sounds like version hell.  mod_python and MySQLdb have to be
 compiled with exactly the same compiler for this to work.

Use of compatible compilers applies to anything you want to use
together. This is nothing specific to mod_python, so this comment is a
bit misleading. These days with with GNU C everywhere, it is hardly
and issue, and was usually only an issue with C++ code and not C code
anyway.

    mod_python is usually troublesome.   Python doesn't really have
 quite enough isolation to run multiple unrelated instances reliably.

The isolation issue is nothing to do with Python itself. Isolation is
an issue in this case, but most likely comes about because the OP is
trying to use both PHP and mod_python together in the same Apache
instance.

In particular, the PHP package is likely loading a MySQL module and it
is linked against a different version of the MySQL client libraries
than what the Python MySQL package is wanting.

People like to blame mod_python for these problems, but it can equally
be attributed to PHP. In practice the reason it shows up as a
mod_python issue is that PHP tries to preload a lot of stuff and so
manages to load its version of shared libraries first. Python with its
lazy loading comes in second, and so conflicts will occur. If
mod_python preloaded stuff like PHP did and this was occurring before
PHP got a chance, it would be the other way around and mod_python
would work fine and PHP would instead be what crashes all the time.

 We use FCGI, which has the isolation of CGI but doesn't reload the
 application for every transaction.  Also, it's easier to debug if
 CPython is crashing.

With the reason that FCGI works being that the processes, even if they
are spawned by Apache, use a fork/exec, thus meaning they have a clean
memory space when starting up.

In summary, look at what version of MySQL libraries are used by PHP
modules and ensure that Python MySQL module is compiled against the
same version.

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


Re: property getter with more than 1 argument?

2008-07-18 Thread [EMAIL PROTECTED]
On 17 juil, 16:57, mk [EMAIL PROTECTED] wrote:
 It seems like getter is defined in such way that it passes only 'self':

 class FunDict(dict):
 def __init__(self):
 self.fundict = dict()

What's the use of inheriting from dict here ???

 def fget(self, fun):

wrong signature for a property.fget callback

 return fundict[fun.func_name]

 def fset(self, newfun):
 self.fundict[newfun.func_name] = newfun

 newfun = property (fget, fset)

   a=FunDict()
  
   a.newfun=f1
  
   a.newfun('f1')

Note that you're passing a string, when your (incorrect) getter
expects a function object.

 Traceback (most recent call last):
File pyshell#67, line 1, in module
  a.newfun('f1')
 TypeError: fget() takes exactly 2 arguments (1 given)

 Is it possible to pass more than one argument to fget function?

Yes : call it directly !-)

Or remember the old saying:

Any software problem can be solved by adding another layer of
indirection. Except, of course, the problem of too much indirection.

Steve Bellovin of ATT Labs

Applied to your problem, it would mean making your getter return a
closure that will take the func or func name and return the result of
the lookup, ie:

def fget(self):
return lambda funcname: self.fundict[funcname]


But anyway: this is still a typical case of arbitrary
overcomplexification. A plain dict would be enough. Or, given the
context (as exposed in an earlier post here), I'd suggest something
like:

class CallbacksRegister(object):
def __init__(self, **kw):
self._store = dict(**kw)
def register(self, func, name=None):
if name is None:
name = func.__name__
self._store(name) = func
return func

def get(self, name, default=None):
return self._store.get(name, default)

def __getattr__(self, name):
try:
return self._store[name]
except KeyError:
raise AttributeError('%s object has no attribute '%s' %
(self, name)

callbacks =  CallbacksRegister()

@callbacks.register
def f1(arg):
print f1, arg

callbacks.f1(yadda)
callbacks.get('f1')('yadda')


 I know: I can define a function with property name ('newfun' in the
 example) and call it with more arguments. But then I do not get the
 benefits of setter and property in general!

The benefit of computed attributes (the property class being only one
possible implementation) is to decouple interface (looks like an
ordinary attribute) from implementation (is in fact computed). And the
benefit from this decoupling is that you don't have to write getters/
setters until you really need them, since you can then turn a plain
attribute into a computed one without breaking the interface.

I fail to see what benefits you get from a property in your above
snippet.
--
http://mail.python.org/mailman/listinfo/python-list


Re: https in pylons

2008-07-18 Thread Graham Dumpleton
On Jul 18, 9:50 pm, [EMAIL PROTECTED] wrote:
 Hello,

 I have a question about framework pylons - how to run(in paster)
 webpages over https? Is it possible, or not?

If Paste server that is uses doesn't already support HTTPS, then run
Pylons under Apache/mod_wsgi, or just run Pylons with Paste server
behind Apache/mod_proxy. In other words, use Apache to handle the
HTTPS side of things.

Graham

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


Re: How to register an extension DLL with python 2.5?

2008-07-18 Thread Boaz Feldbaum
OK, found it! I just had to give my dll a new file extension: PYD, that is 
rename it from foo.dll to foo.pyd

Boaz Feldbaum [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hello all,

 I wrote an extension dll in C++ using VS2005 to be used in windows 
 platform. In pyhon 2.4 I used to copy my dll to the dlls sub-directory of 
 python installation and import my dll and it worked fine. This doesn't 
 work with python 2.5. I get the following when trying to import my dll:

 import pywutil
 Traceback (most recent call last):
  File stdin, line 1, in module
 ImportError: No module named pywutil


 What should I do in 2.5 to be able to import my extension dll?

 Thanks a lot in advance,
 Boaz.
 


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


Core Dump - Segmentation Fault -Newbie

2008-07-18 Thread johnericaturnbull
Hi - I am very new to python. I get this random core dump and am
looking for a good way to catch the error. I know the function my core
dump occurs. Is there any error catching/handling that I could use in
python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best Python packages?

2008-07-18 Thread Iain King
On Jul 18, 11:23 am, Ben Sizer [EMAIL PROTECTED] wrote:
 On Jul 16, 3:31 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:

  Ben Sizer wrote:
   make my development a lot easier.

  Knowing what kind of development you do might help, of course.  Some
  libraries are excellent in some contexts and suck badly in others...

 Sure. Mostly I'm just interested in what's out there though. In C++
 you have Boost which everybody knows are a source of high quality
 libraries, covering a fairly wide set of applications. Obviously
 that's more low-level and less application specific, and the Python
 standard libs do pretty much everything that is in Boost, but it's
 that sort of peer-reviewed and widely-applicable list that I'd like to
 see.

 I (attempt to) use TurboGears for web development and that depends on
 a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch,
 SimpleJson, FormEncode, etc - and I would never have heard of these if
 TurboGears' exposure of its internals wasn't so common. Some of these
 are web-specific but some are not. And I'd never know to look for them
 specificially, because in many cases it wouldn't occur to me that they
 exist. (eg. Object-Relational Mappers like SQLObject may be obvious if
 you come from certain areas of IT, but I'd never heard of them before
 I started with TurboGears.)

 For what it's worth, my main areas of interest are gaming, multimedia,
 and web development. But I just like to hear about anything that
 people might use which makes their life a lot easier and which perhaps
 is not application specific - like ORMs or something similar.

  Looking at things that larger projects and distributions use can also be
  a good idea.  For example, if you're doing scientific stuff, go directly
  to enthought.com.  If you're doing web stuff, look at the libraries big
  Django applications use.  Etc.

 Sadly, I know just as little about what major applications are out
 there as I do about what libraries are out there!

 --
 Ben Sizer

Well, if you're looking for a list of excellent 3rd party Python
libraries, then I can give you the ones I like and use a lot:
wxPython :  powerful GUI library which generates native look 
feel
PIL :   Imaging Library - if you need to manipulate bitmaps
pyGame :SDL for python
BeautifulSoup : for real-world (i.e. not-at-all-recommendation-
compliant) HTML processing

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


Re: Question on Joining of list

2008-07-18 Thread ptn
On Jul 18, 5:40 am, SUBHABRATA [EMAIL PROTECTED] wrote:
 Hi Peter,Peter Otten wrote:
  SUBHABRATA wrote:

   Thanx Peter,
   I would change my variables next time I would post.

  No, you should use meaningful variable names when you write your code no
  matter whether you plan to post it or not.

 Good You are teaching me something good in life. Thanx.

   And obviously,
   thanx for your solution. I am reviewing it, I was also trying out some
   solutions.

  You misunderstood. I did not modify your code other than changing the
  variable names. My hope was that with this modification any errors sprang
  to you eye...

 I was seeing that.
 I am almost near the solution. You can also try some hands if you
 feel.
 Best Regards,
 Subhabrata.



  Peter



A couple more things on variable naming and coding style:

- You used a{digit} to name variables of different types (a4 was an
int, a2 was a list and the rest were strings). Remember C, where i, j,
k are indices, p, q, r are pointers, s, t are strings and x, y, z are
integers. For unimportant variables, you can skip long descriptive
names, so long you don't use a confusing one.

- You violated your own naming conventions. Why did you choose to use
s to name that last string? Use descriptive names and stick to your
own style.

- You use whitespace weirdly (like in a4-1 or a4=a3.find).

Try reading PEP8 (http://www.python.org/dev/peps/pep-0008/), the Style
Guide for Python Code.

As for your code, you need to find where it is that missing_word and
first_char are being updated, and assign to s before that happens.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Core Dump - Segmentation Fault -Newbie

2008-07-18 Thread phil lemelin
I would suggest importing traceback.


import traceback

try :
  mystuff
except :
 print str(traceback.format_exc())

But in the case of a SegFault or core dump, it might not help you at all.

Can you post part of the function ?


On Fri, Jul 18, 2008 at 9:25 AM, [EMAIL PROTECTED] wrote:

 Hi - I am very new to python. I get this random core dump and am
 looking for a good way to catch the error. I know the function my core
 dump occurs. Is there any error catching/handling that I could use in
 python?
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
Philippe-Alexandre Lemelin
--
http://mail.python.org/mailman/listinfo/python-list

Re: Core Dump - Segmentation Fault -Newbie

2008-07-18 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
 Hi - I am very new to python. I get this random core dump and am
 looking for a good way to catch the error. I know the function my core
 dump occurs. Is there any error catching/handling that I could use in
 python?

Since you are using Windows, this is somewhat non-trivial due to the lack of
tools shipped by Microsoft. Are you really getting crashes of the interpreter
and not just an exception with a stacktrace?

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


Re: Regular expression help

2008-07-18 Thread Russell Blau
[EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 I am new to Python, with a background in scientific computing. I'm
 trying to write a script that will take a file with lines like

 c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647
 3pv=0

 extract the values of afrac and etot and plot them.
...

 What is being stored in energy is '_sre.SRE_Match object at
 0x2a955e4ed0', not '-11.020107'. Why?

because the re.match() method returns a match object, as documented at 
http://www.python.org/doc/current/lib/match-objects.html

But this looks like a problem where regular expressions are overkill. 
Assuming all your lines are formatted as in the example above (every value 
you are interested in contains an equals sign and is surrounded by spaces), 
you could do this:

values = {}
for expression in line.split( ):
if = in expression:
name, val = expression.split(=)
values[name] = val

I'd wager that this will run a fair bit faster than any regex-based 
solution.  Then you just use values['afrac'] and values['etot'] when you 
need them.

And when you get to be a really hard-core Pythonista, you could write the 
whole routine above in one line, but this seems clearer.  ;-)

Russ



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


Re: Core Dump - Segmentation Fault -Newbie

2008-07-18 Thread johnericaturnbull
On Jul 18, 9:56 am, Stefan Behnel [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  Hi - I am very new to python. I get this random core dump and am
  looking for a good way to catch the error. I know the function my core
  dump occurs. Is there any error catching/handling that I could use in
  python?

 Since you are using Windows, this is somewhat non-trivial due to the lack of
 tools shipped by Microsoft. Are you really getting crashes of the interpreter
 and not just an exception with a stacktrace?

 Stefan

Hi - thanks for responding. I am actually running on linux. Does this
make a difference? Also the error shown is:

 myFunction call failed. Segmentation Fault (core dumped)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Core Dump - Segmentation Fault -Newbie

2008-07-18 Thread Doug Morse
On Fri, 18 Jul 2008 15:56:10 +0200, Stefan Behnel [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] wrote:
  Hi - I am very new to python. I get this random core dump and am
  looking for a good way to catch the error. I know the function my core
  dump occurs. Is there any error catching/handling that I could use in
  python?
 
  Since you are using Windows, this is somewhat non-trivial due to the lack of
  tools shipped by Microsoft. Are you really getting crashes of the interpreter
  and not just an exception with a stacktrace?
 
  Stefan

Hi John,

Well, I must be missing something re: why Stefan states that you are using
Windows.  I don't see that stated in your original post, and, AFAIK, the
phrase core dump is seen much more in the Unix world than in the Windows
world.

So, just in case you are on some *nix variant, you can of course log all the
system calls up until your core dump by running:

$ strace -o logfile.txt python [...]

where [...] should be replaced with any parameters to the python interpreter,
such as the Python script you're running, e.g., 

$ strace -o logfile.txt python Hello.py

The trace of system calls will be in the file logfile.txt.  For more info on
strace, see the strace(1) man page (i.e., run man strace).

Doug

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


Re: Regular expression help

2008-07-18 Thread Brad

[EMAIL PROTECTED] wrote:

Hello,

I am new to Python, with a background in scientific computing. I'm
trying to write a script that will take a file with lines like

c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647
3pv=0

extract the values of afrac and etot...


Why not just split them out instead of using REs?

fp = open(test.txt)
lines = fp.readlines()
fp.close()

for line in lines:
split = line.split()
for pair in split:
pair_split = pair.split(=)
if len(pair_split) == 2:
try:
print pair_split[0], is, pair_split[1]
except:
pass

Results:

IDLE 1.2.2   No Subprocess 

afrac is .7
mmom is 0
sev is -9.56646
erep is 0
etot is -11.020107
emad is -3.597647
3pv is 0

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


Re: substitution of list elements

2008-07-18 Thread [EMAIL PROTECTED]
On 18 juil, 14:33, antar2 [EMAIL PROTECTED] wrote:
 I want to replace each first element in list 5 that is equal to the
 first element of the list of lists4 by the fourth element. I wrote
 following code that does not work:

 list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q',
 'f']]
 list5 = ['1', '2', '3']

 for j in list4:
   for k in list5:
 if j[0] == k:
 k = j[3]
 print list5
 Wanted result: ['c', 'e', '3']

 thanks!

select = lambda item, lst: (item, lst[3])[item == lst[0]]
list5[:] = [select(*pair) for pair in zip(list5, list4)]

# or if you prefer a more procedural solution:

for index, (item, lst) in enumerate(zip(list5, list4)):
if item == lst[0]:
list5[index] = lst[3]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression help

2008-07-18 Thread Gerard flanagan

[EMAIL PROTECTED] wrote:

Hello,

I am new to Python, with a background in scientific computing. I'm
trying to write a script that will take a file with lines like

c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647
3pv=0

extract the values of afrac and etot and plot them. I'm really
struggling with getting the values of efrac and etot. So far I have
come up with (small snippet of script just to get the energy, etot):

def get_data_points(filename):
file = open(filename,'r')
data_points = []
while 1:
line = file.readline()
if not line: break
energy = get_total_energy(line)
data_points.append(energy)
return data_points

def get_total_energy(line):
rawstr = r(?Pkey.*?)=(?Pvalue.*?)\s
p = re.compile(rawstr)
return p.match(line,5)

What is being stored in energy is '_sre.SRE_Match object at
0x2a955e4ed0', not '-11.020107'. Why? 




1. Consider using the 'split' method on each line rather than regexes
2. In your code you are compiling the regex for every line in the file, 
you should lift it out of the 'get_total-energy' function so that the 
compilation is only done once.
3. A Match object has a 'groups' function which is what you need to 
retrieve the data

4. Also look at the findall method:

data = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 
emad=-3.597647 3pv=0 '


import re

rx = re.compile(r'(\w+)=(\S+)')

data = dict(rx.findall(data))

print data

hth

G.

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


Help with decorators

2008-07-18 Thread Mr SZ
Hi,

I'm using decos for the first time.I want to check the input and then call a 
function in a class.

I'm pasting the code:

    def check_input_sanity(self,rover_input):
        '''Check the input from client'''
        def _check(fn):
            def _inner(rover_input):
                if 
rover_input[0].upper().replace('L','').replace('R').replace('M') == '' and 
rover_input[1].upper() in ['N','S','E','W']:
                    print 'Input is sane'    
                    fn()
                return _inner
        return _check            
    
        
   
    @check_input_sanity([self.origorient,self.direction_str,self.init_loc])
    def tell_coord_from_path(self):
        '''Gives the final co-ordinate and the direction untill it falls 
off/reaches.'''
        pdir = self.origorient #Present direction


here the vars : self.origorient,self.direction_str,self.init_loc are the ones I 
would like to check for sanity.
But I get an error:

Traceback (most recent call last):
  File tw.py, line 5, in module
    import sys,os,robo
  File C:\Python25\thought\robo.py, line 30, in module
    class robo_actions(robo):
  File C:\Python25\thought\robo.py, line 58, in robo_actions
    @check_input_sanity([self.origorient,self.direction_str,self.init_loc])
NameError: name 'self' is not defined

Why is this so? aren't they to be referred to by self with in a class as they 
are attributes of the object ?
 life isn't heavy enough,it flies away and floats far above action


  Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au--
http://mail.python.org/mailman/listinfo/python-list

Re: Regular expression help

2008-07-18 Thread Nick Dumas
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

I think you're over-complicating this. I'm assuming that you're going to
do a line graph of some sorta, and each new line of the file contains a
new set of data.

The problem you mentioned with your regex returning a match object
rather than a string is because you're simply using a re function that
doesn't return strings. re.findall() is what you want. That being said,
here is working code to mine data from your file.

[code]
line = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107
mad=-3.597647 3pv=0'

energypat = r'\betot=(-?\d*?[.]\d*)'

#Note: To change the data grabbed from the line, you can change the
#'etot' to 'afrac' or 'emad' or anything that doesn't contain a regex
#special character.

energypat = re.compile(energypat)

re.findall(energypat, line)# returns a STRING containing '-12.020107'

[/code]

This returns a string, which is easy enough to convert to an int. After
that, you can datapoints.append() to your heart's content. Good luck
with your work.

[EMAIL PROTECTED] wrote:
 Hello,
 
 I am new to Python, with a background in scientific computing. I'm
 trying to write a script that will take a file with lines like
 
 c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647
 3pv=0
 
 extract the values of afrac and etot and plot them. I'm really
 struggling with getting the values of efrac and etot. So far I have
 come up with (small snippet of script just to get the energy, etot):
 
 def get_data_points(filename):
 file = open(filename,'r')
 data_points = []
 while 1:
 line = file.readline()
 if not line: break
 energy = get_total_energy(line)
 data_points.append(energy)
 return data_points
 
 def get_total_energy(line):
 rawstr = r(?Pkey.*?)=(?Pvalue.*?)\s
 p = re.compile(rawstr)
 return p.match(line,5)
 
 What is being stored in energy is '_sre.SRE_Match object at
 0x2a955e4ed0', not '-11.020107'. Why? I've been struggling with
 regular expressions for two days now, with no luck. Could someone
 please put me out of my misery and give me a clue as to what's going
 on? Apologies if it's blindingly obvious or if this question has been
 asked and answered before.
 
 Thanks,
 
 Nicole
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkiAqiAACgkQLMI5fndAv9h7HgCfU6a7v1nE5iLYcUPbXhC6sfU7
mpkAn1Q/DyOI4Zo7QJhF9zqfqCq6boXv
=L2VZ
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if an object IS in a list

2008-07-18 Thread nicolas . pourcelot
 What is your (concrete) use case, by the way?



I try to make it simple (there is almost 25000 lines of code...)
I have a sheet with geometrical objects (points, lines, polygons,
etc.)
The sheet have an object manager.

So, to simplify :

 sheet.objects.A = Point(0, 0)
 sheet.objects.B = Point(0, 2)
 sheet.objects.C = Middle(A, B)

Then we have :

 sheet.objects.A == sheet.objects.B
True

since have and B have the same coordinates.
But of course A and B objects are not same python objects.
In certain cases, some geometrical objects are automatically
referenced in the sheet, without being defined by the user.
(Edges for polygons, for example...)
But they must not be referenced twice. So if the edge of the polygon
is already referenced (because the polygon uses an already referenced
object for its construction...), it must not be referenced again.
However, if there is an object, which accidentally have the same
coordinates, it must be referenced with a different name.

So, I use something like this in 'sheet.objects.__setattr__(self,
name, value)':
if type(value) == Polygon:
for edge in value.edges:
if edge is_in sheet.objects.__dict__.itervalues():
object.__setattr__(self, self.__new_name(), edge)

Ok, I suppose it's confused, but it's difficult to sum up. ;-)

 Another possibility :-)
 from itertools import imap
 id(x) in imap(id, items)

I didn't know itertools.
Thanks :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression help

2008-07-18 Thread nclbndk759
On Jul 18, 3:35 pm, Nick Dumas [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 I think you're over-complicating this. I'm assuming that you're going to
 do a line graph of some sorta, and each new line of the file contains a
 new set of data.

 The problem you mentioned with your regex returning a match object
 rather than a string is because you're simply using a re function that
 doesn't return strings. re.findall() is what you want. That being said,
 here is working code to mine data from your file.

 [code]
 line = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107
 mad=-3.597647 3pv=0'

 energypat = r'\betot=(-?\d*?[.]\d*)'

 #Note: To change the data grabbed from the line, you can change the
 #'etot' to 'afrac' or 'emad' or anything that doesn't contain a regex
 #special character.

 energypat = re.compile(energypat)

 re.findall(energypat, line)# returns a STRING containing '-12.020107'

 [/code]

 This returns a string, which is easy enough to convert to an int. After
 that, you can datapoints.append() to your heart's content. Good luck
 with your work.



 [EMAIL PROTECTED] wrote:
  Hello,

  I am new to Python, with a background in scientific computing. I'm
  trying to write a script that will take a file with lines like

  c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647
  3pv=0

  extract the values of afrac and etot and plot them. I'm really
  struggling with getting the values of efrac and etot. So far I have
  come up with (small snippet of script just to get the energy, etot):

  def get_data_points(filename):
      file = open(filename,'r')
      data_points = []
      while 1:
          line = file.readline()
          if not line: break
          energy = get_total_energy(line)
          data_points.append(energy)
      return data_points

  def get_total_energy(line):
      rawstr = r(?Pkey.*?)=(?Pvalue.*?)\s
      p = re.compile(rawstr)
      return p.match(line,5)

  What is being stored in energy is '_sre.SRE_Match object at
  0x2a955e4ed0', not '-11.020107'. Why? I've been struggling with
  regular expressions for two days now, with no luck. Could someone
  please put me out of my misery and give me a clue as to what's going
  on? Apologies if it's blindingly obvious or if this question has been
  asked and answered before.

  Thanks,

  Nicole

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

 iEYEARECAAYFAkiAqiAACgkQLMI5fndAv9h7HgCfU6a7v1nE5iLYcUPbXhC6sfU7
 mpkAn1Q/DyOI4Zo7QJhF9zqfqCq6boXv
 =L2VZ
 -END PGP SIGNATURE-

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


[ANN] PyStar 0.1 -- A* graph search algorithm

2008-07-18 Thread Glenn Hutchings
Announcing PyStar, a python module implementing the A* graph search
algorithm.  Available under the GPL, you can find it at

http://fluffybunny.memebot.com/pystar.html

I tried to find a decent Python version of this on the Interweb, but the
only one I found (http://arainyday.se/projects/python/AStar) was just a bit
too cryptic for me to understand and use.  So I knocked this up from
pseudocode on the Wikipedia A* page, and rewrote the AStar demo program in
Tkinter.

Comments, bug reports, big wads of cash, etc., are welcome.
--
http://mail.python.org/mailman/listinfo/python-list


Re: trying to match a string

2008-07-18 Thread Andrew Freeman

oj wrote:

On Jul 18, 12:10 pm, John Machin [EMAIL PROTECTED] wrote:
  

On Jul 18, 9:05 pm, oj [EMAIL PROTECTED] wrote:





On Jul 18, 11:33 am, [EMAIL PROTECTED] wrote:
  

Hi,

Hi,

I am taking a string as an input from the user and it should only

contain the chars:L , M or R

I tried the folllowing in kodos but they are still not perfect:

[^A-K,^N-Q,^S-Z,^0-9]

[L][M][R]
[LRM]?L?[LRM]? etc but they do not exactly meet what I need.

For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that.

regards,

SZ

The string may or may not have all the three chars.


With regular expressions, [^LRM] matches a character that isn't L, R
or M. So:
  
import re
  
var = LRLRLRLNR
  
if re.search(r'[^LRM]', var):

print Invalid
  

Fails if var refers to the empty string.



No it doesn't, it succeeds if var is an empty string. An empty string
doesn't contain characters that are not L, R or M.

The OP doesn't specify whether an empty string is valid or not. My
interpretation was that an empty string would be valid.
  

Why not just use * instead of + like:

if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of string; $ 
means end of string
   print Invalid

This will *only* print invalid when there is a character other than L, R, or M 
or a empty string.



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


Re: trying to match a string

2008-07-18 Thread Andrew Freeman

Andrew Freeman wrote:

oj wrote:

On Jul 18, 12:10 pm, John Machin [EMAIL PROTECTED] wrote:
 

On Jul 18, 9:05 pm, oj [EMAIL PROTECTED] wrote:



   

On Jul 18, 11:33 am, [EMAIL PROTECTED] wrote:
 

Hi,
Hi,
I am taking a string as an input from the user and it 
should only

contain the chars:L , M or R
I tried the folllowing in kodos but they are still not 
perfect:

[^A-K,^N-Q,^S-Z,^0-9]
[L][M][R]
[LRM]?L?[LRM]? etc but they do not exactly meet what I need.
For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' 
.like that.

regards,
SZ
The string may or may not have all the three chars.


With regular expressions, [^LRM] matches a character that isn't L, R
or M. So:
  import re
  var = LRLRLRLNR
  if re.search(r'[^LRM]', var):
print Invalid
  

Fails if var refers to the empty string.



No it doesn't, it succeeds if var is an empty string. An empty string
doesn't contain characters that are not L, R or M.

The OP doesn't specify whether an empty string is valid or not. My
interpretation was that an empty string would be valid.
  

Why not just use * instead of + like:

if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of 
string; $ means end of string

   print Invalid

This will *only* print invalid when there is a character other than L, 
R, or M or a empty string.


Sorry, forget the beginning and ending markers, I just tried it out, it 
doesn't work.

use this instead:


if re.search(r'[^LRM]*', var):
  print Invalid
--
http://mail.python.org/mailman/listinfo/python-list


Re: trying to match a string

2008-07-18 Thread arni
On Jul 18, 7:51 pm, Andrew Freeman [EMAIL PROTECTED] wrote:
 Andrew Freeman wrote:
  oj wrote:
  On Jul 18, 12:10 pm, John Machin [EMAIL PROTECTED] wrote:

  On Jul 18, 9:05 pm, oj [EMAIL PROTECTED] wrote:

  On Jul 18, 11:33 am, [EMAIL PROTECTED] wrote:

  Hi,
          Hi,
          I am taking a string as an input from the user and it
  should only
  contain the chars:L , M or R
          I tried the folllowing in kodos but they are still not
  perfect:
          [^A-K,^N-Q,^S-Z,^0-9]
  [L][M][R]
  [LRM]?L?[LRM]? etc but they do not exactly meet what I need.
          For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N'
  .like that.
          regards,
  SZ
          The string may or may not have all the three chars.

  With regular expressions, [^LRM] matches a character that isn't L, R
  or M. So:
        import re
        var = LRLRLRLNR
        if re.search(r'[^LRM]', var):
      print Invalid

  Fails if var refers to the empty string.

  No it doesn't, it succeeds if var is an empty string. An empty string
  doesn't contain characters that are not L, R or M.

  The OP doesn't specify whether an empty string is valid or not. My
  interpretation was that an empty string would be valid.

  Why not just use * instead of + like:

  if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of
  string; $ means end of string
     print Invalid

  This will *only* print invalid when there is a character other than L,
  R, or M or a empty string.

 Sorry, forget the beginning and ending markers, I just tried it out, it
 doesn't work.
 use this instead:

 if re.search(r'[^LRM]*', var):
    print Invalid

I was using kodos to check the regex.I should have used the IDE
instead.Thanks a lot again.
--
http://mail.python.org/mailman/listinfo/python-list


create PyString

2008-07-18 Thread Torsten Mohr
Hi,

in an extension module i'd like to create a very large PyString.
As the string is very large i'd first like to create the string
and let Python allocate the space for it and then fill it from
my code.

But the only interface that i can find in Python/stringobject.h
is:

PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t);

But my extension module does not have the data consecutively in memory.

If i'd use this function i'd first have to allocate the data, construct the
string and then let python _again_ allocate the same amount of memory
and copy my data.


Is there a way to tell python to:
1. let python create a PyString with an allocated buffer
2. let my extension module fill the buffer
3. let python validate the strings hash value and whatever else is
necessary?


Thanks for any hints,
Torsten.

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


Re: Unusual Exception Behaviour

2008-07-18 Thread Vinay Sajip
On Jul 18, 12:03 pm, Robert Rawlins
[EMAIL PROTECTED] wrote:

 Yeah it's got me a little bemused to be honest, I've tried playing around
 with configuration options this morning and not been able to achieve
 anything that works properly.


The logging configuration functionality provided by fileConfig is all-
or-nothing, i.e. it does not support incremental configuration.

Do you know if any libraries you depend on use fileConfig?

If you use programmatic configuration only, and don't use fileConfig
at all, does everything work as expected?

Regards,

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


Re: x, = y (???)

2008-07-18 Thread Andrew Freeman

kj wrote:


I just came across an assignment of the form

  x, = y

where y is a string (in case it matters).

1. What's the meaning of the comma in the LHS of the assignment?
2. How could I have found this out on my own?

(Regarding (2) above, I consulted the index of several Python
reference books but I could not find the answer to (1).  I hope to
find a better Python reference!)

TIA!

kynn
  


Try this:
 y = 'abc'
 type(y)
type 'str'
 type((y,))
type 'tuple'
 y = y,   # y, is just short for (y,) you *have* to use a coma in 1 
length tuples

 y
('abc',)
 type(y)
type 'tuple'
 y[0]
'abc'
 x, = y   #same as x = y[0] OR more verbosely (x,) = (y,)
 x
'abc'
 type(x)
type 'str'

Maybe that will hape you understand what the comma is for?
--
http://mail.python.org/mailman/listinfo/python-list


Python evening class

2008-07-18 Thread lloyd


I am learning about python but I would like to attend and evening class at 
college as I find it hard to study at home.  Does anyone know of such a class 
in London UK?
 

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


Re: Core Dump - Segmentation Fault -Newbie

2008-07-18 Thread Stefan Behnel
Doug Morse wrote:
 Well, I must be missing something re: why Stefan states that you are using
 Windows.  I don't see that stated in your original post

It's stated in the mail headers of his post, though. That's the problem with
newbies - you never know where that stops being right.

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


Re: Regular expression help

2008-07-18 Thread Marc 'BlackJack' Rintsch
On Fri, 18 Jul 2008 10:04:29 -0400, Russell Blau wrote:

 values = {}
 for expression in line.split( ):
 if = in expression:
 name, val = expression.split(=)
 values[name] = val
 […]

 And when you get to be a really hard-core Pythonista, you could write
 the whole routine above in one line, but this seems clearer.  ;-)

I know it's a matter of taste but I think the one liner is still clear
(enough)::

  values = dict(s.split('=') for s in line.split() if '=' in s)

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

Re: Converting from local - UTC

2008-07-18 Thread M.-A. Lemburg

On 2008-07-18 05:28, Dennis Lee Bieber wrote:

On Thu, 17 Jul 2008 20:26:11 -0300, Gabriel Genellina
[EMAIL PROTECTED] declaimed the following in comp.lang.python:


Note that I used %s everywhere (it's just a placeholder, not a format) and  


cue the beer commercial

Unfortunately, in the case of MySQLdb... It is both -- maybe that
will change once MySQLdb gives up compatibility with MySQL 4.x by
incorporating usage of prepared statements in place of a Python %
interpolation.

It has to be %s as the adapter first converts to string, escapes,
and quotes the arguments; regardless of native datatype they are strings
when put into the SQL statement...


If you prefer a different parameter style, you could use mxODBC
and the MySQL ODBC drivers.

You'd then write:

query = INSERT INTO image VALUES(?, ?, ?, ?)

and avoid any confusion due to the parameter style looking a
lot like the Python string formatting markers (for obvious
reasons, since that's what the MySQLdb module uses internally).

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jul 18 2008)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Tcl extensions with Python?

2008-07-18 Thread C Martin
On Jul 17, 5:18 pm, Guilherme Polo [EMAIL PROTECTED] wrote:
[snip]
 And.. for tkpng specifically, you won't need tk.call to use it, you
 just need to create your images using Tkinter.PhotoImage with a png
 type.

Thank you Guilherme, that's all great info.

 Thomas Troeger [EMAIL PROTECTED] wrote:
 ARGH, Tcl!!! ;-) I know that's not the question, but do you know PIL
 (http://www.pythonware.com/products/pil)?

Yes, I know about PIL. However, I need use PNGs with a full alpha
channel. PIL only seems support simple transparency, whereas TkPNG
seems to work as expected with them. If I am incorrect in this, then
please let me know how to use it!

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


Re: x, = y (???)

2008-07-18 Thread kj
In [EMAIL PROTECTED] Matthew Woodcraft [EMAIL PROTECTED] writes:

kj wrote:
 I still don't get it.  If we write 

  y  = 'Y'
  x, = y

 what's the difference now between x and y?  And if there's no
 difference, what's the point of performing such unpacking?

If y really is is a string, I think it's likely that the line you came
across was a typo.


OK, this is the best explanation I've seen for the code I'm talking about.

This code may be found at:

  http://norvig.com/sudo.py

in the definition of the function eliminate.  Here's the fragment:

elif len(values[s]) == 1:
## If there is only one value (d2) left in square, remove it from peers
d2, = values[s]

Now, in the assignment, values[s] *is* a string of length 1.  So
this assignment appears to me entirely equivalent (in its ultimate
effect) to the more straightforward

d2 = values[s]

...but, since I'm a noob, I thought I'd ask :-)

Thanks!

kynn
-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >