Re: adding new function

2010-06-23 Thread Gabriel Genellina
En Tue, 22 Jun 2010 14:18:59 -0300, Terry Reedy   
escribió:

On 6/22/2010 5:44 AM, Daniel Fetchinson wrote:

how can i simply add new functions to module after its initialization
(Py_InitModule())?  I'm missing something like
PyModule_AddCFunction().


in Python, for modules written in python

import mymod
mymod.fname = somefunc #or
setattr(mymod, namestring, funcobject)


I presume you use the C-API equivalent of setattr.


That one, or PyModule_AddObject (just for nicer error messages really).

--
Gabriel Genellina

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


Re: Book review / advise

2010-06-23 Thread Stephen Hansen
On 6/22/10 9:45 PM, John Bokma wrote:
> Stephen Hansen  writes:
> 
>> I *have* seen people burned by confusion over situations *extremely*
>> similar to this;
> 
> But is it? You didn't even ask yourself that question.

Yes. I did.

I don't really make a point of publishing internal dialog on mailing
lists for you to determine though, so I can see the confusion.

>> If being concerned about fellow Python-folks possibly getting ripped off
>> makes me an asshat, so be it. Go y'know-what yourself.
> 
> If this publisher is legimate you might very well be denying
> people -- like I said I am interested -- from getting a print-out in the
> future just because /you/ cried wolf and called them scammers.

Uh, yeah. Okay.

The level of utter absurdity in that statement is off the charts.

I am not off starting some great interweb campaign to bring them down.
I'm not logging into Amazon and down-rating all the books and giving
them scathing reviews. I haven't notified any agencies (from Amazon, to
the PSF) who may be interested in the scam (if it is a scam) to try to
get action done. I haven't even considered registering
sohobooksisascam.com to try to get the word out. Not that having an
anti-website is any good when there's no website to go all anti against,
but whatever.

On a mailing list, a guy with no real influence or and absolutely no
importance, questioned the validity of the publisher and the legitimacy
and ethical behavior they're doing.

If they can't stand up to one question-- they aren't legitimate.

I "deny" nothing to anyone by raising a concern. If the concern is
unfounded, great. If it isn't, then some people will be saved some grief.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna' )

2010-06-23 Thread Gabriel Genellina

En Tue, 22 Jun 2010 11:02:58 -0300,  escribió:


Python 2.6.4 (Win32): Anyone have any explanation for the
following

encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna'
)

Given that other processes may have to use the output of these
methods, what is the recommended technique?

Demonstration:


import encodings.idna
name = u'junk\xfc\xfd.txt'
name

u'junk\xfc\xfd.txt'

encodings.idna.ToASCII( name )

'xn--junk.txt-95ak'

name.encode( 'idna' )

'xn--junk-3rag.txt'

encodings.idna.ToUnicode( encodings.idna.ToASCII( name ) )

u'junk\xfc\xfd.txt'

name.encode( 'idna' ).decode( 'idna' )

u'junk\xfc\xfd.txt'


IDNA is *specifically* designed to operate with domain names, not  
arbitrary text. (IDNA = Internationalizing Domain Names in Applications).  
Even the encoding/decoding part alone(punycode) is specifically tailored  
for use in domain names. Do not use it for any other purpose.


That said, it seems that encodings.idna.ToUnicode/ToAscii work on  
individual 'labels' only (a domain name is comprised of several labels  
separated by '.') -- and encode/decode('idna') takes the whole name,  
splits, and processes each label (following RFC 3490, I presume)


--
Gabriel Genellina

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


Re: adding new function

2010-06-23 Thread Christian Heimes
Am 22.06.2010 19:18, schrieb Terry Reedy:
> On 6/22/2010 5:44 AM, Daniel Fetchinson wrote:
>>> how can i simply add new functions to module after its initialization
>>> (Py_InitModule())?  I'm missing something like
>>> PyModule_AddCFunction().
> 
> in Python, for modules written in python
> 
> import mymod
> mymod.fname = somefunc #or
> setattr(mymod, namestring, funcobject)

For C code, it's a more complex. You have to construct a proper C
function PyObject* from a PyMethodDef* first. See
Python/modsupport.c:Py_InitModule4().

Christian

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


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread Jean-Michel Pichavant

rantingrick wrote:

---

On Jun 22, 4:29 am, Jean-Michel Pichavant 
wrote:
  

This is a python list, fully dedicated to our dutch semi God. So how can
you even immagine that someone here will suggest you to go for rub...
sorry I can't prononce this blasphemous name.



---


...After reading these comments i reminisce back to a time when a good
friend of this community "r" said basically the same things but was
lynched for them. 


That's because "r" is the first letter of Ruby, try "p" and everybody 
will love you (that makes me think that Perl should be renamed as it 
outrageously share the same 1st character with Python).


JM

PS : I have no idea about Ruby, never used it, so I still don't 
understand why you quote me in  your anti-ruby post

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


Re: "isinstance" question

2010-06-23 Thread Thomas Jollans
On 06/23/2010 08:39 AM, Satish Eerpini wrote:
> 
> 
>   I want to test whether an object is an instance of any
> user-defined
> class.  "isinstance" is less helpful than one would expect.
> 
>  >>> import types
>  >>> class foo() : # define dummy class
> ... pass
> ...
>  >>> x = foo()
>  >>>
>  >>> type(x)
> 
>  >>>
>  >>> isinstance(x, types.ClassType)
> False
>  >>> isinstance(x, types.InstanceType)
> True
>  >>> foo
> 
>  >>> x
> <__main__.foo instance at 0x020080A8>
> 
> So far, so good. x is an InstanceType.  But let's try a
> class with a constructor:
> 
>  >>> class bar(object) :
> ...def __init__(self, val) :
> ...  self.val = val
> ...
>  >>> b = bar(100)
>  >>> b
> <__main__.bar object at 0x01FF50D0>
>  >>> isinstance(b, types.InstanceType)
> False
>  >>> isinstance(b, types.ClassType)
> False
>  >> bar
> 
> 
> well the same code on my side returns true when you run isinstance(b,
> types.InstanceType) even when the class has a constructor. Why is there
> a difference in the output when we are both using Cython 2.6 ?? (2.6.4
> to be exact)

I assume you mean CPython, not Cython.

As Gabriel said, the difference is that bar is a subclass of object. If
isinstance(bar(100), types.InstanceType), then you did not subclass
object, and get an old-style class.


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


example of multi threads

2010-06-23 Thread Mag Gam
I am looking for a simple multi threaded  example.

Lets say I have to ssh to 20 servers and I would like to that in
parallel. Can someone please provide a an example for that?

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


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread hackingKK
Ruby is a nice language to learn, but I seem to find it less matured.  
That might be my own personal perception.
But looking at its success which you can read on Pythonology, I think it 
is going to be my choice and of many others for a long time to come.

Besides ruby is more popular due to the rails attached to it.
Happy hacking.
Krishnakant.

On Wednesday 23 June 2010 02:10 PM, Jean-Michel Pichavant wrote:

rantingrick wrote:

---

On Jun 22, 4:29 am, Jean-Michel Pichavant 
wrote:
This is a python list, fully dedicated to our dutch semi God. So how 
can

you even immagine that someone here will suggest you to go for rub...
sorry I can't prononce this blasphemous name.


---


...After reading these comments i reminisce back to a time when a good
friend of this community "r" said basically the same things but was
lynched for them. 


That's because "r" is the first letter of Ruby, try "p" and everybody 
will love you (that makes me think that Perl should be renamed as it 
outrageously share the same 1st character with Python).


JM

PS : I have no idea about Ruby, never used it, so I still don't 
understand why you quote me in  your anti-ruby post


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


Re: example of multi threads

2010-06-23 Thread Stefan Behnel

Mag Gam, 23.06.2010 12:24:

I am looking for a simple multi threaded  example.

Lets say I have to ssh to 20 servers and I would like to that in
parallel. Can someone please provide a an example for that?


Sounds like you want to run background processes, not threads. Take a look 
at the subprocess module.


Stefan

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


Instance method decorator garbage collection problem

2010-06-23 Thread John Reid

Hi,

I've written a decorator that prints exceptions and I'm having some 
trouble with garbage collection.


My decorator is:

import sys
def print_exception_decorator(fn):
def decorator(self, *args, **kwds):
try:
return fn(*args, **kwds)
except:
print 'Exception:', sys.exc_info()
raise
return decorator



The class I want to decorate the methods of is:

class InstanceCounted(object):
"A class that keeps track of how many instances there are."
count = 0
def __init__(self):
InstanceCounted.count += 1
def __del__(self):
InstanceCounted.count -= 1

class A(InstanceCounted):
"A class that I want to decorate a method on."
def __init__(self):
super(A, self).__init__()
self.method = print_exception_decorator(self.method)

def __del__(self):
del self.method

def method(self):
pass



When I run the following it does not seem like my object 'a' is garbage 
collected:


print 'Have %d instances' % InstanceCounted.count
print 'Creating A'
a = A()
print 'Have %d instances' % InstanceCounted.count
print 'Deleting A'
del a
print 'Have %d instances' % InstanceCounted.count


This is the output:

Have 0 instances
Creating A
Have 1 instances
Deleting A
Have 1 instances


The InstanceCounted.count is 1 at the end. If I omit the call to 
"self.method = print_exception_decorator(self.method)" then the instance 
count goes down to 0 as desired. I thought that the decorator might be 
holding a reference to the instance through the bound method, so I added 
 the __del__() but it doesn't fix the problem.


Can anyone suggest anything? Is my technique to decorate bound methods 
not a good one? How else should I decorate a bound method?


Thanks in advance,
John.


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


Re: Instance method decorator garbage collection problem

2010-06-23 Thread Thomas Jollans
On 06/23/2010 01:40 PM, John Reid wrote:
> Hi,
> 
> I've written a decorator that prints exceptions and I'm having some
> trouble with garbage collection.
> 
> My decorator is:
> 
> import sys
> def print_exception_decorator(fn):
> def decorator(self, *args, **kwds):
> try:
> return fn(*args, **kwds)
> except:
> print 'Exception:', sys.exc_info()
> raise
> return decorator
> 
> 
> 
> The class I want to decorate the methods of is:
> 
> class InstanceCounted(object):
> "A class that keeps track of how many instances there are."
> count = 0
> def __init__(self):
> InstanceCounted.count += 1
> def __del__(self):
> InstanceCounted.count -= 1
> 
> class A(InstanceCounted):
> "A class that I want to decorate a method on."
> def __init__(self):
> super(A, self).__init__()
> self.method = print_exception_decorator(self.method)
> 
> def __del__(self):
> del self.method
> 
> def method(self):
> pass
> 
> 
> 
> When I run the following it does not seem like my object 'a' is garbage
> collected:
> 
> print 'Have %d instances' % InstanceCounted.count
> print 'Creating A'
> a = A()
> print 'Have %d instances' % InstanceCounted.count
> print 'Deleting A'
> del a
> print 'Have %d instances' % InstanceCounted.count
> 
> 
> This is the output:
> 
> Have 0 instances
> Creating A
> Have 1 instances
> Deleting A
> Have 1 instances
> 
> 
> The InstanceCounted.count is 1 at the end. If I omit the call to
> "self.method = print_exception_decorator(self.method)" then the instance
> count goes down to 0 as desired. I thought that the decorator might be
> holding a reference to the instance through the bound method, so I added
>  the __del__() but it doesn't fix the problem.

Adding __del__ like this does "fix the problem", but it introduces a new
one: lacking a call to super().__del__, you simply don't decrement the
instance count.

To decorate a method, you'd best just decorate it normally. I doubt your
technique will work anyway, as the function returned by the decorator
isn't bound to the object, you'd need to pass one self reference
implicitly, which is then thrown away.

simply,

def exc_decor(fn):
@functools.wraps(fn)
def wrapper(*args, **keywords):
try:
return fn(*args, **keywords):
except:
#...
raise
return wrapper

class X(...):
   @exc_decor
   def foo(self, arg):
  pass

(if targeting pre-decorator Python, the code would look different of course)

This way, the function itself is decorated, and the function returned by
the decorator is bound to the object. It'll just work as expected, no
trickery required.

-- Thomas

> 
> Can anyone suggest anything? Is my technique to decorate bound methods
> not a good one? How else should I decorate a bound method?
> 
> Thanks in advance,
> John.
> 
> 

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


Re: Instance method decorator garbage collection problem

2010-06-23 Thread Peter Otten
John Reid wrote:

> Hi,
> 
> I've written a decorator that prints exceptions and I'm having some
> trouble with garbage collection.
> 
> My decorator is:
> 
> import sys
> def print_exception_decorator(fn):
>  def decorator(self, *args, **kwds):
>  try:
>  return fn(*args, **kwds)
>  except:
>  print 'Exception:', sys.exc_info()
>  raise
>  return decorator
> 
> 
> 
> The class I want to decorate the methods of is:
> 
> class InstanceCounted(object):
>  "A class that keeps track of how many instances there are."
>  count = 0
>  def __init__(self):
>  InstanceCounted.count += 1
>  def __del__(self):
>  InstanceCounted.count -= 1
> 
> class A(InstanceCounted):
>  "A class that I want to decorate a method on."
>  def __init__(self):
>  super(A, self).__init__()
>  self.method = print_exception_decorator(self.method)
> 
>  def __del__(self):
>  del self.method
> 
>  def method(self):
>  pass
> 
> 
> 
> When I run the following it does not seem like my object 'a' is garbage
> collected:
> 
> print 'Have %d instances' % InstanceCounted.count
> print 'Creating A'
> a = A()
> print 'Have %d instances' % InstanceCounted.count
> print 'Deleting A'
> del a
> print 'Have %d instances' % InstanceCounted.count
> 
> 
> This is the output:
> 
> Have 0 instances
> Creating A
> Have 1 instances
> Deleting A
> Have 1 instances
> 
> 
> The InstanceCounted.count is 1 at the end. If I omit the call to
> "self.method = print_exception_decorator(self.method)" then the instance
> count goes down to 0 as desired. I thought that the decorator might be
> holding a reference to the instance through the bound method, so I added
>   the __del__() but it doesn't fix the problem.
> 
> Can anyone suggest anything? Is my technique to decorate bound methods
> not a good one? How else should I decorate a bound method?

The problem is that cyclic garbage collection cannot cope with __del__() 
methods. Quoting http://docs.python.org/library/gc.html#gc.garbage

"""
Objects that have __del__() methods and are part of a reference cycle cause 
the entire reference cycle to be uncollectable
"""

The best workaround is to control the object's lifetime explicitly by 
turning it into a context manager, see

http://docs.python.org/reference/datamodel.html#with-statement-context-
managers

or providing a close() method and use contextlib:

>>> class A(object):
... def close(self):
... print "break cycles here"
...
>>> class A(object):
... def __init__(self):
... self.self = self
... def __del__(self):
... print "bye"
... def close(self):
... print "breaking cycles here"
... del self.self
...
>>> a = A()
>>> del a
>>> import contextlib
>>> with contextlib.closing(A()) as b:
... print "using b"
...
using b
breaking cycles here
>>> del b
bye

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


Re: Instance method decorator garbage collection problem

2010-06-23 Thread Christian Heimes
> The InstanceCounted.count is 1 at the end. If I omit the call to 
> "self.method = print_exception_decorator(self.method)" then the instance 
> count goes down to 0 as desired. I thought that the decorator might be 
> holding a reference to the instance through the bound method, so I added 
>   the __del__() but it doesn't fix the problem.

Adding __del__ introduces a whole bunch of new issues with cyclic gc.
http://docs.python.org/library/gc.html#gc.garbage

> Can anyone suggest anything? Is my technique to decorate bound methods 
> not a good one? How else should I decorate a bound method?

You shouldn't use __del__ to count your instances. Instead you can use
sys.getrefcount() and gc.get_objects() or use a weakref with a callback.

Christian

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


Re: Instance method decorator garbage collection problem

2010-06-23 Thread John Reid



Thomas Jollans wrote:

The InstanceCounted.count is 1 at the end. If I omit the call to
"self.method = print_exception_decorator(self.method)" then the instance
count goes down to 0 as desired. I thought that the decorator might be
holding a reference to the instance through the bound method, so I added
 the __del__() but it doesn't fix the problem.


Adding __del__ like this does "fix the problem", but it introduces a new
one: lacking a call to super().__del__, you simply don't decrement the
instance count.


Now that's a good point! I've added super().__del__ but the problem 
remains for some reason. My A class now looks like:


class A(InstanceCounted):
"A class that I want to decorate a method on."
def __init__(self):
super(A, self).__init__()
self.method = print_exception_decorator(self.method)

def __del__(self):
super(A, self).__del__()
del self.method

def method(self):
pass


Did you try this?



To decorate a method, you'd best just decorate it normally. I doubt your
technique will work anyway, as the function returned by the decorator
isn't bound to the object, you'd need to pass one self reference
implicitly, which is then thrown away.


Looking at the original post, I had included an extra "self" in the 
argument list


def decorator(self, *args, **kwds):

should have been

def decorator(*args, **kwds):


With this correction my method decorates instance methods on objects 
successfully although I don't know why the garbage collection isn't working.






simply,

def exc_decor(fn):
@functools.wraps(fn)
def wrapper(*args, **keywords):
try:
return fn(*args, **keywords):
except:
#...
raise
return wrapper

class X(...):
   @exc_decor
   def foo(self, arg):
  pass

(if targeting pre-decorator Python, the code would look different of course)

This way, the function itself is decorated, and the function returned by
the decorator is bound to the object. It'll just work as expected, no
trickery required.


Thanks for this. I remember having some problems decorating instance 
methods in the past which is why I started doing it as in the original 
post. Your method seems just fine though.


Thanks,
John.

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


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread Ed Keith
--- On Wed, 6/23/10, Stephen Hansen  wrote:

> From: Stephen Hansen 
> Subject: Re: Should I Learn Python or Ruby next?
> To: python-list@python.org
> Date: Wednesday, June 23, 2010, 1:51 AM
> On 6/22/10 10:39 PM, Dennis Lee
> Bieber wrote:
> > On Tue, 22 Jun 2010 15:55:51 -0700, Stephen Hansen
> > 
> declaimed the following in
> > gmane.comp.python.general:
> > 
> >> I second Forth. Learning and using that was --
> slightly painful, but
> > 
> >     Just pick up any advanced HP
> programmable calculator... RPL is a
> > close substitute 
> 
> That's just a start. The reverse and stack-oriented nature
> of the
> language makes you have to start thinking in an interesting
> way, and
> sure, a RPL/stack-calculator can get that for you.
> 
> But then going on and doing real programming with it,
> making your own
> words (functions), ... its fun.
> 
> -- 
> 
>    Stephen Hansen
>    ... Also: Ixokai
>    ... Mail: me+list/python (AT) ixokai
> (DOT) io
>    ... Blog: http://meh.ixokai.io/
> 
> 
> -Inline Attachment Follows-
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I agree you should learn a DIFFERENT programming language. Perl, Python, & Ruby 
are all quite similar. If you want to expand your horizons, learn one of the 
following:

  Forth -lots of fun.

  Assembler - give you a much better understanding of what is really happening 
under the hood.

  Prolog - a very different way of thinking.

Give one of them a try.

   -EdK

Ed Keith
e_...@yahoo.com

Blog: edkeith.blogspot.com





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


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread Ed Keith

--- On Wed, 6/23/10, Dennis Lee Bieber  wrote:

> From: Dennis Lee Bieber 
> Subject: Re: Should I Learn Python or Ruby next?
> To: python-list@python.org
> Date: Wednesday, June 23, 2010, 1:39 AM
> On Tue, 22 Jun 2010 15:55:51 -0700,
> Stephen Hansen
> 
> declaimed the following in
> gmane.comp.python.general:
> 
> > I second Forth. Learning and using that was --
> slightly painful, but
> 
>     Just pick up any advanced HP
> programmable calculator... RPL is a
> close substitute 
> 
> > really invigorating. And I also second learning a
> functional language
> > (though I don't know if I'd inflict Haskell on
> anyone).
> >
> 
>     Is APL still available?
>         4 5 $rho 20 ? 52
> (using a common means for lack of greek keyboard)
> -- 
>     Wulfraed       
>          Dennis Lee
> Bieber         AF6VN
>         wlfr...@ix.netcom.com 
>   HTTP://wlfraed.home.netcom.com/
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
Try J. It does not require a special keyboard.

-EdK

Ed Keith
e_...@yahoo.com

Blog: edkeith.blogspot.com




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


Another MySQL Problem

2010-06-23 Thread Victor Subervi
Hi;
I have this line:

  cursor.execute('select clientEmail from clients where client=%s',
(string.replace(client, '_', ' ')))
  clientEmail = cursor.fetchone()[0]
  cursor.execute('select * from %s' % (client))

client = "Lincoln_Properties"
With the replacement, the interpreter complains that mydatabase.Lincoln
doesn't exist. Therefore, the first line of code isn't putting the %s
replacement in quotes, as I was told by you all it would. So I add quotes to
it and the interpreter complains on the second line of code that it's
unsubscriptable (because it's None). What gives?
TIA
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread Dave Angel

Stephen Hansen wrote:

On 6/22/10 10:39 PM, Dennis Lee Bieber wrote:
  

On Tue, 22 Jun 2010 15:55:51 -0700, Stephen Hansen
 declaimed the following in
gmane.comp.python.general:



I second Forth. Learning and using that was -- slightly painful, but
  

Just pick up any advanced HP programmable calculator... RPL is a
close substitute 



That's just a start. The reverse and stack-oriented nature of the
language makes you have to start thinking in an interesting way, and
sure, a RPL/stack-calculator can get that for you.

But then going on and doing real programming with it, making your own
words (functions), ... its fun.

  
And two places where it differs from nearly every other language:  when 
you define your own flow-control enhancements to the language (e.g. 
WHILE is not a keyword, it's merely a function), and when you finally 
understand dodoes (that's "Do Does").


DaveA

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


Re: Another MySQL Problem

2010-06-23 Thread Stephen Hansen
On 6/23/10 6:45 AM, Victor Subervi wrote:
> Hi;
> I have this line:
> 
>   cursor.execute('select clientEmail from clients where client=%s',
> (string.replace(client, '_', ' ')))
>   clientEmail = cursor.fetchone()[0]
>   cursor.execute('select * from %s' % (client))
> 
> client = "Lincoln_Properties"
> With the replacement, the interpreter complains that mydatabase.Lincoln
> doesn't exist. Therefore, the first line of code isn't putting the %s
> replacement in quotes, as I was told by you all it would. So I add
> quotes to it and the interpreter complains on the second line of code
> that it's unsubscriptable (because it's None). What gives?

Its very early, so excuse me if I fall asleep in the middle of the response.

First: Don't do 'string.replace(your_string, x, y)' -- that's back in
the very, very old days before strings themselves had all the nice methods.

Do, 'client.replace("_", " ")' instead.

Second, you're forgetting a cardinal rule. Always, always, always,
include the actual tracebacks when reporting errors. Don't summarize them.

Third, I *think* the problem is-- though I may be wrong here, because
again, just woke up-- that you're not passing the options as a tuple.

Consider: ("hello") is not a tuple with one item. This is a slight
'wart' with Python syntax. Parens do not make tuples: *commas* do.
Therefore, every tuple *must* have a comma. To make a one-item tuple,
you must do ("hello", )

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Parsing email

2010-06-23 Thread Xianwen Chen
Hi guys,

I use these codes to read emails from an IMAP server:

import imaplib

imap_srv_addr = "someserver"
imap_srv = imaplib.IMAP4_SSL(imap_srv_addr)
imap_srv.login("username","passwd")
imap_srv.select("Inbox")
msg = imap_srv.fetch(1, '(RFC822)')

How can I parse msg so it can be appended to the other IMAP server?

Best regards,

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


Re: Another MySQL Problem

2010-06-23 Thread Victor Subervi
On Wed, Jun 23, 2010 at 10:25 AM, Stephen Hansen
wrote:

> On 6/23/10 6:45 AM, Victor Subervi wrote:
> > Hi;
> > I have this line:
> >
> >   cursor.execute('select clientEmail from clients where client=%s',
> > (string.replace(client, '_', ' ')))
> >   clientEmail = cursor.fetchone()[0]
> >   cursor.execute('select * from %s' % (client))
> >
> > client = "Lincoln_Properties"
> > With the replacement, the interpreter complains that mydatabase.Lincoln
> > doesn't exist. Therefore, the first line of code isn't putting the %s
> > replacement in quotes, as I was told by you all it would. So I add
> > quotes to it and the interpreter complains on the second line of code
> > that it's unsubscriptable (because it's None). What gives?
>
> Its very early, so excuse me if I fall asleep in the middle of the
> response.
>
> First: Don't do 'string.replace(your_string, x, y)' -- that's back in
> the very, very old days before strings themselves had all the nice methods.
>
> Do, 'client.replace("_", " ")' instead.
>
> Second, you're forgetting a cardinal rule. Always, always, always,
> include the actual tracebacks when reporting errors. Don't summarize them.
>
> Third, I *think* the problem is-- though I may be wrong here, because
> again, just woke up-- that you're not passing the options as a tuple.
>
> Consider: ("hello") is not a tuple with one item. This is a slight
> 'wart' with Python syntax. Parens do not make tuples: *commas* do.
> Therefore, every tuple *must* have a comma. To make a one-item tuple,
> you must do ("hello", )
>

Well making the changes you suggest throws this error:

A problem occurred in a Python script. Here is the sequence of function
calls leading up to the error, in the order they occurred.
 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
   67 
   68 '''
   69
   70 mailSpreadsheet()
   71
mailSpreadsheet = 
 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py in
mailSpreadsheet()
   34   subject = 'Order From Client'
   35   cursor.execute('select clientEmail from clients where client="%s"',
(client.replace('_', ' '),))
   36   clientEmail = cursor.fetchone()[0]
   37   cursor.execute('select * from %s', (client,))
   38   data = cursor.fetchall()
clientEmail = 'jp...@lpc.com', cursor = ,
cursor.fetchone = >

TypeError: unsubscriptable object
  args = ('unsubscriptable object',)

Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Stephen Hansen
On 6/23/10 8:16 AM, Victor Subervi wrote:
> On Wed, Jun 23, 2010 at 10:25 AM, Stephen Hansen
> mailto:pyt...@ixokai.io>> wrote:
> 
> On 6/23/10 6:45 AM, Victor Subervi wrote:
> > Hi;
> > I have this line:
> >
> >   cursor.execute('select clientEmail from clients where client=%s',
> > (string.replace(client, '_', ' ')))
> >   clientEmail = cursor.fetchone()[0]
> >   cursor.execute('select * from %s' % (client))
> >
> > client = "Lincoln_Properties"
> > With the replacement, the interpreter complains that
> mydatabase.Lincoln
> > doesn't exist. Therefore, the first line of code isn't putting the %s
> > replacement in quotes, as I was told by you all it would. So I add
> > quotes to it and the interpreter complains on the second line of code
> > that it's unsubscriptable (because it's None). What gives?
> 
> Its very early, so excuse me if I fall asleep in the middle of the
> response.
> 
> First: Don't do 'string.replace(your_string, x, y)' -- that's back in
> the very, very old days before strings themselves had all the nice
> methods.
> 
> Do, 'client.replace("_", " ")' instead.
> 
> Second, you're forgetting a cardinal rule. Always, always, always,
> include the actual tracebacks when reporting errors. Don't summarize
> them.
> 
> Third, I *think* the problem is-- though I may be wrong here, because
> again, just woke up-- that you're not passing the options as a tuple.
> 
> Consider: ("hello") is not a tuple with one item. This is a slight
> 'wart' with Python syntax. Parens do not make tuples: *commas* do.
> Therefore, every tuple *must* have a comma. To make a one-item tuple,
> you must do ("hello", )
> 
> 
> Well making the changes you suggest throws this error:
> 
> A problem occurred in a Python script. Here is the sequence of function
> calls leading up to the error, in the order they occurred.
>  /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
> 
>67 
>68 '''
>69
>70 mailSpreadsheet()
>71
> mailSpreadsheet = 
>  /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
>  in mailSpreadsheet()
>34   subject = 'Order From Client'
>35   cursor.execute('select clientEmail from clients where
> client="%s"', (client.replace('_', ' '),))
>36   clientEmail = cursor.fetchone()[0]
>37   cursor.execute('select * from %s', (client,))
>38   data = cursor.fetchall()
> clientEmail = 'jp...@lpc.com ', cursor =
> , cursor.fetchone =  Cursor.fetchone of >
> 
> TypeError: unsubscriptable object
>   args = ('unsubscriptable object',)

Generally speaking, though this may not be true for MySQL (I don't use
it as a rule), double quotes in SQL often have a special meaning that is
distinct from what you're used to in programming languages.

I.e., cur.execute('SELECT blah FROM blah WHERE blah = "hello"') is not
necessecarily the same as if you had spelled that last bit 'hello'. This
isn't universal across all SQL engines, but its something to keep in
mind. Basically: always use single quotes.

That said: you don't quote things when using parameterized statements.
You write, cur.execute("SELECT ... client = %s", ("my string",)) and not
"%s" in there. You did mention you switched this around at some point
earlier, but you had other problems then so there's no telling if those
other problems are what caused it not to work.

I'm assuming its line 36 which threw the error: cgitb includes some
lines after, so its non obvious when you're looking at it in plain text.
You should note the line number in such cases in case there's more then
one line nearby which looks possibly suspect.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Simon Malinge
On Wed, 23 Jun 2010 10:46:37 -0430, Victor Subervi
 wrote:
> On Wed, Jun 23, 2010 at 10:25 AM, Stephen Hansen
> wrote:
> 
>> On 6/23/10 6:45 AM, Victor Subervi wrote:
>> > Hi;
>> > I have this line:
>> >
>> >   cursor.execute('select clientEmail from clients where client=%s',
>> > (string.replace(client, '_', ' ')))
>> >   clientEmail = cursor.fetchone()[0]
>> >   cursor.execute('select * from %s' % (client))
>> >
>> > client = "Lincoln_Properties"
>> > With the replacement, the interpreter complains that
mydatabase.Lincoln
>> > doesn't exist. Therefore, the first line of code isn't putting the %s
>> > replacement in quotes, as I was told by you all it would. So I add
>> > quotes to it and the interpreter complains on the second line of code
>> > that it's unsubscriptable (because it's None). What gives?
>>
>> Its very early, so excuse me if I fall asleep in the middle of the
>> response.
>>
>> First: Don't do 'string.replace(your_string, x, y)' -- that's back in
>> the very, very old days before strings themselves had all the nice
>> methods.
>>
>> Do, 'client.replace("_", " ")' instead.
>>
>> Second, you're forgetting a cardinal rule. Always, always, always,
>> include the actual tracebacks when reporting errors. Don't summarize
>> them.
>>
>> Third, I *think* the problem is-- though I may be wrong here, because
>> again, just woke up-- that you're not passing the options as a tuple.
>>
>> Consider: ("hello") is not a tuple with one item. This is a slight
>> 'wart' with Python syntax. Parens do not make tuples: *commas* do.
>> Therefore, every tuple *must* have a comma. To make a one-item tuple,
>> you must do ("hello", )
>>
> 
> Well making the changes you suggest throws this error:
> 
> A problem occurred in a Python script. Here is the sequence of function
> calls leading up to the error, in the order they occurred.
>  /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
>67 
>68 '''
>69
>70 mailSpreadsheet()
>71
> mailSpreadsheet = 
>  /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py in
> mailSpreadsheet()
>34   subject = 'Order From Client'
>35   cursor.execute('select clientEmail from clients where
client="%s"',
> (client.replace('_', ' '),))
>36   clientEmail = cursor.fetchone()[0]
>37   cursor.execute('select * from %s', (client,))
>38   data = cursor.fetchall()
> clientEmail = 'jp...@lpc.com', cursor = ,
> cursor.fetchone =  object>>
> 
> TypeError: unsubscriptable object
>   args = ('unsubscriptable object',)
> 
> Please advise.
> TIA,
> beno

You should strongly consider reading the DB API 2.0 documentation :
http://www.python.org/dev/peps/pep-0249/

.fetchone() 
  
Fetch the next row of a query result set, returning a
single sequence, or None when no more data is
available. [6]

You script fails because the request returns no results, and fetchone()
returns None.
Evaluating None[0] is invalid, so you get an exception.

Test fetchone() return value before accessing it as a sequence, and
everything should be OK :

row = cursor.fetchone()
if row is None:
# error handling, i.e.:
raise CustomException("Client not found")
clientEmail = row[0]
...

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


Does a '_sre.SRE_Pattern' have state,or is it thread-safe?

2010-06-23 Thread John Nagle

   '_sre.SRE_Pattern' is what "re.compile" returns.

   Is that a mutable object, with state that changes
during the parse, or is it an immutable constant?  Can
two threads use the same '_sre.SRE_Pattern' at the same time?

   (I'm writing something to find race conditions in existing code,
which is why all these obscure introspection-related questions.)

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


Re: Another MySQL Problem

2010-06-23 Thread Paul Rubin
Stephen Hansen  writes:
>On 6/23/10 6:45 AM, Victor Subervi wrote:
>>   cursor.execute('select clientEmail from clients where client=%s', ...
> Do, 'client.replace("_", " ")' instead.

Er, look what happened to Little Bobby Tables (a quick web search on his
name should find his story) because someone wrote code like that.
Really, write the code a different way, with a prepared query.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Tapi
On Wed, 23 Jun 2010 10:46:37 -0430, Victor Subervi
 wrote:
> On Wed, Jun 23, 2010 at 10:25 AM, Stephen Hansen
> wrote:
> 
>> On 6/23/10 6:45 AM, Victor Subervi wrote:
>> > Hi;
>> > I have this line:
>> >
>> >   cursor.execute('select clientEmail from clients where client=%s',
>> > (string.replace(client, '_', ' ')))
>> >   clientEmail = cursor.fetchone()[0]
>> >   cursor.execute('select * from %s' % (client))
>> >
>> > client = "Lincoln_Properties"
>> > With the replacement, the interpreter complains that
mydatabase.Lincoln
>> > doesn't exist. Therefore, the first line of code isn't putting the %s
>> > replacement in quotes, as I was told by you all it would. So I add
>> > quotes to it and the interpreter complains on the second line of code
>> > that it's unsubscriptable (because it's None). What gives?
>>
>> Its very early, so excuse me if I fall asleep in the middle of the
>> response.
>>
>> First: Don't do 'string.replace(your_string, x, y)' -- that's back in
>> the very, very old days before strings themselves had all the nice
>> methods.
>>
>> Do, 'client.replace("_", " ")' instead.
>>
>> Second, you're forgetting a cardinal rule. Always, always, always,
>> include the actual tracebacks when reporting errors. Don't summarize
>> them.
>>
>> Third, I *think* the problem is-- though I may be wrong here, because
>> again, just woke up-- that you're not passing the options as a tuple.
>>
>> Consider: ("hello") is not a tuple with one item. This is a slight
>> 'wart' with Python syntax. Parens do not make tuples: *commas* do.
>> Therefore, every tuple *must* have a comma. To make a one-item tuple,
>> you must do ("hello", )
>>
> 
> Well making the changes you suggest throws this error:
> 
> A problem occurred in a Python script. Here is the sequence of function
> calls leading up to the error, in the order they occurred.
>  /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
>67 
>68 '''
>69
>70 mailSpreadsheet()
>71
> mailSpreadsheet = 
>  /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py in
> mailSpreadsheet()
>34   subject = 'Order From Client'
>35   cursor.execute('select clientEmail from clients where
client="%s"',
> (client.replace('_', ' '),))
>36   clientEmail = cursor.fetchone()[0]
>37   cursor.execute('select * from %s', (client,))
>38   data = cursor.fetchall()
> clientEmail = 'jp...@lpc.com', cursor = ,
> cursor.fetchone =  object>>
> 
> TypeError: unsubscriptable object
>   args = ('unsubscriptable object',)
> 
> Please advise.
> TIA,
> beno

You should strongly consider reading the DB API 2.0 documentation :
http://www.python.org/dev/peps/pep-0249/

.fetchone() 
  
Fetch the next row of a query result set, returning a
single sequence, or None when no more data is
available. [6]

You script fails because the request returns no results, and fetchone()
returns None.
Evaluating None[0] is invalid, so you get an exception.

Test fetchone() return value before accessing it as a sequence, and
everything should be OK :

row = cursor.fetchone()
if row is None:
# error handling, i.e.:
raise CustomException("Client not found")
clientEmail = row[0]
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Tim Chase

On 06/23/2010 08:45 AM, Victor Subervi wrote:

Hi;
I have this line:

   cursor.execute('select clientEmail from clients where client=%s',
(string.replace(client, '_', ' ')))
   clientEmail = cursor.fetchone()[0]
   cursor.execute('select * from %s' % (client))

client = "Lincoln_Properties"
With the replacement, the interpreter complains that mydatabase.Lincoln
doesn't exist. Therefore, the first line of code isn't putting the %s
replacement in quotes, as I was told by you all it would. So I add quotes to
it and the interpreter complains on the second line of code that it's
unsubscriptable (because it's None). What gives?


First, you don't specify which .execute() is throwing the 
exception.  My guess is the 2nd.  However, a little side-tour:


---[side tour]--

Well, while I'm not sure whether it's the root of your problem, 
notice that the parameters should be


  cursor.execute(sql, tuple_of_parameters)

Notice the difference between

  print type((string.replace(client, '_', ' '))) # string
  print type((string.replace(client, '_', ' '),)) # tuple

returns...hint, what you have is not a single-element tuple as 
execute() expects.  Once you're passing an expected tuple, it 
should properly escape it.  You might be getting a peculiar 
side-effect of MySQL's DB-escaping (that string-formatting with a 
non-tuple parameter acts like a one-element-tuple).  However, 
internally, coercion-to-tuple may be happening (as it may well on 
a different DB backend), so you might be getting something like


  tuple(replaced_string)

which gives you something weird like

  ('L', 'i', 'n', ...)

but if that was the case, I'd expect it would complain with a 
"TypeError: not all arguments converted during string formatting" 
unless the DB backend does smarter parsing of the parameters.


Additionally, using module version of string.replace() has been 
deprecated in favor of just using the method on available on all 
strings:


  client.replace("_", " ")

---[end side tour]--

Verify that the value for "client" has the underscore in it 
before you do your 2nd execute -- if the exception is what I 
think it is, it sounds like you're creating the SQL with the 
wrong client string.  Verify it by pulling it out as a parameter:


sql = 'select * from %s' % (client)
print repr(sql)
cursor.execute(sql)

and verify that your SQL isn't

  'select * from Lincoln Properties'

If your tablename does violate best practices by having a space 
in it, then you'd need to hand-escape with whatever means MySQL 
offers for escaping table/column/view names.  In SQL Server, it's


  [Lincoln Properties]

and in some others, I think it would be

  `Lincoln Properties`

However, it's generally considered bad-practice to have 
object-names (tables, columns, views, indexes, triggers, 
stored-procedures, etc) that have spaces in their names.


-tkc


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


Re: Another MySQL Problem

2010-06-23 Thread Victor Subervi
Ok, let's start all over again. When I have this code:

  cursor.execute('select clientEmail from clients where client="%s"',
(client.replace('_', ' '),))
  clientEmail = cursor.fetchone()[0]

I get this error:

 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
   67 
   68 '''
   69
   70 mailSpreadsheet()
   71
mailSpreadsheet = 
 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py in
mailSpreadsheet()
   34   subject = 'Order From Client'
   35   cursor.execute('select clientEmail from clients where client="%s"',
(client.replace('_', ' '),))
   36   clientEmail = cursor.fetchone()[0]
   37   cursor.execute('select * from %s', (client,))
   38   data = cursor.fetchall()
clientEmail = 'jp...@lpc.com', cursor = ,
cursor.fetchone = >

TypeError: unsubscriptable object
  args = ('unsubscriptable object',)

When I have this code:

  print 'select clientEmail from clients where client="%s"' %
(client.replace('_', ' '),)
  cursor.execute('select clientEmail from clients where client=%s',
(client.replace('_', ' '),))
  clientEmail = cursor.fetchone()[0]

It prints this:


select clientAppelation, clientLast, clientEmail from clients where
client="Lincoln Properties" select clientEmail from clients where
client="Lincoln Properties"

and throws this error:

Traceback (most recent call last):
  File "/var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py", line 71,
in ?
mailSpreadsheet()
  File "/var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py", line 38,
in mailSpreadsheet
cursor.execute('select * from %s', (client,))
  File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in
execute
self.errorhandler(self, exc, value)
  File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35,
in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to
use near ''Lincoln Properties'' at line 1")

Clearly, the results should not be "None". Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


the bugerrd code

2010-06-23 Thread Victoria Hernandez
The new mision I herits the buggered code (i do not the bugger). How
do debugger him? Tahnk you very much. Vikhy :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Stephen Hansen
On Jun 23, 2010, at 9:12 AM, Paul Rubin  wrote:

Stephen Hansen  writes:

On 6/23/10 6:45 AM, Victor Subervi wrote:

 cursor.execute('select clientEmail from clients where client=%s', ...

Do, 'client.replace("_", " ")' instead.


Er, look what happened to Little Bobby Tables (a quick web search on his
name should find his story) because someone wrote code like that.
Really, write the code a different way, with a prepared query.


I think you misread. He is using parameterized queries-- just
incorrectly, as addressed later that you didn't quote. He isn't using
string formatting to generate the SQL. The mysql layer just uses %s as
a marker.

The line you did quote was just about using string methods for the
data to pass into the parameterized query-- not for SQL purposes but
just because the data in the table apparently has spaces and the data
in this part of his app has underscores. For some reason.

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


Re: Another MySQL Problem

2010-06-23 Thread Stephen Hansen
On Jun 23, 2010, at 9:28 AM, Victor Subervi  wrote:

Ok, let's start all over again. When I have this code:

  cursor.execute('select clientEmail from clients where client="%s"',
(client.replace('_', ' '),))
  clientEmail = cursor.fetchone()[0]


Already addressed this. Do not quote inside the SQL.


I get this error:

 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
   67 
   68 '''
   69
   70 mailSpreadsheet()
   71
mailSpreadsheet = 
 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py in
mailSpreadsheet()
   34   subject = 'Order From Client'
   35   cursor.execute('select clientEmail from clients where client="%s"',
(client.replace('_', ' '),))
   36   clientEmail = cursor.fetchone()[0]


First do not use [0] om fetchone-- it returns one or None. Test if none.

It is returning NOne because there is no value that matched-- or those
quotes I said to remove are messing it up.

   37   cursor.execute('select * from %s', (client,))


Even when you fix the above this wont work-- this is so bad.

You can only use parameterized queries-- the execute with the comma followed
by a tuple-- yo insert into the SQL data VALUES after the WHERE clause...
Not table names, not column names. SQL object names should be static.

You should not have a table named (client)_properties for each client. You
should have a table named properties with a field (which may be part of our
primary key) called client or some such, which contains the client name.

Its ok for a single table to have a lot of data.


When I have this code:

  print 'select clientEmail from clients where client="%s"' %
(client.replace('_', ' '),)
  cursor.execute('select clientEmail from clients where client=%s',
(client.replace('_', ' '),))
  clientEmail = cursor.fetchone()[0]


The problem is not this line but:


  File "/var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py", line 38,
in mailSpreadsheet
cursor.execute('select * from %s', (client,))


This one. See above.

--Stephen via iPad.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book review / advise

2010-06-23 Thread John Bokma
Stephen Hansen  writes:

> On 6/22/10 9:48 PM, John Bokma wrote:

[..]

> Its when you package it up in such a way that the buyer doesn't realize
> what they're buying, that's where the problem comes-- and that's what is
> happening quite a lot these days.

Which is not the case here.

> If it looks like a scam, take care personally. If it looks like a scam
> and someone is asking about it, you don't sit by and say nothing. That's
> inhuman.

Yelling scam because you have a gut feeling is probably human, but I
wouldn't call it ethical.

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does a '_sre.SRE_Pattern' have state,or is it thread-safe?

2010-06-23 Thread Stephen Hansen
On Jun 23, 2010, at 9:10 AM, John Nagle  wrote:

>   '_sre.SRE_Pattern' is what "re.compile" returns.
>
>   Is that a mutable object, with state that changes
> during the parse, or is it an immutable constant?  Can
> two threads use the same '_sre.SRE_Pattern' at the same time?

Ouch. I hope it is thread safe or I have some problems. But: since
compiled regular expressions are automatically cached and used when
one throws non compiled expressions into re, ISTM they have to be
thread safe. Or we'd have tons of problems.

--Stephen via iPad.
-- 
http://mail.python.org/mailman/listinfo/python-list


ttk Scale: missing attributes

2010-06-23 Thread Alan G Isaac

Tkinter's Scale widget had a `label` and a `resolution` attribute.
These appear to be missing from the Ttk Scale widget.
Is there a reason?  These were important attributes.

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


Re: Does a '_sre.SRE_Pattern' have state,or is it thread-safe?

2010-06-23 Thread MRAB

John Nagle wrote:

   '_sre.SRE_Pattern' is what "re.compile" returns.

   Is that a mutable object, with state that changes
during the parse, or is it an immutable constant?  Can
two threads use the same '_sre.SRE_Pattern' at the same time?

   (I'm writing something to find race conditions in existing code,
which is why all these obscure introspection-related questions.)


A compiled pattern instance is immutable and threadsafe.

BTW, its methods don't release the GIL, so even if it wasn't threadsafe,
it would still be safe. :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Instance method decorator garbage collection problem

2010-06-23 Thread Thomas Jollans
On 06/23/2010 02:56 PM, John Reid wrote:
> 
> 
> Thomas Jollans wrote:
>>> The InstanceCounted.count is 1 at the end. If I omit the call to
>>> "self.method = print_exception_decorator(self.method)" then the instance
>>> count goes down to 0 as desired. I thought that the decorator might be
>>> holding a reference to the instance through the bound method, so I added
>>>  the __del__() but it doesn't fix the problem.
>>
>> Adding __del__ like this does "fix the problem", but it introduces a new
>> one: lacking a call to super().__del__, you simply don't decrement the
>> instance count.
> 
> Now that's a good point! I've added super().__del__ but the problem
> remains for some reason. My A class now looks like:
> 
> class A(InstanceCounted):
> "A class that I want to decorate a method on."
> def __init__(self):
> super(A, self).__init__()
> self.method = print_exception_decorator(self.method)
> 
> def __del__(self):
> super(A, self).__del__()
> del self.method
> 
> def method(self):
> pass
> 
> 
> Did you try this?

No, I didn't. And, as Peter Otten pointed out, it wouldn't work anyway.
But this will work:

##

import sys
from functools import wraps

def print_exc(func):
@wraps(func)
def wrapper(*a, **kwa):
try:
return func(*a, **kwa)
except:
print 'Exception', sys.exc_info()
raise
return wrapper

class InstanceCounted(object):
count = 0
def __init__(self):
type(self).count += 1

def __del__(self):
type(self).count -= 1

class TestClass(InstanceCounted):
def __init__(self):
print 'TestClass initialized'
super(TestClass, self).__init__()

@print_exc
def testmethod(self):
print "Heureka", self

if __name__ == '__main__':
print '%d instances!' % TestClass.count
TestClass()
print '%d instances!' % TestClass.count
t = TestClass()
print '%d instances!' % TestClass.count
t.testmethod()
t2 = TestClass()
print '%d instances!' % TestClass.count
del t2
print '%d instances!' % TestClass.count
del t
print '%d instances!' % TestClass.count




And the output is:

0 instances!
TestClass initialized
0 instances!
TestClass initialized
1 instances!
Heureka <__main__.TestClass object at 0x7f39a6fc2ad0>
TestClass initialized
2 instances!
1 instances!
0 instances!


> 
>>
>> To decorate a method, you'd best just decorate it normally. I doubt your
>> technique will work anyway, as the function returned by the decorator
>> isn't bound to the object, you'd need to pass one self reference
>> implicitly, which is then thrown away.
> 
> Looking at the original post, I had included an extra "self" in the
> argument list
> 
> def decorator(self, *args, **kwds):
> 
> should have been
> 
> def decorator(*args, **kwds):
> 
> 
> With this correction my method decorates instance methods on objects
> successfully although I don't know why the garbage collection isn't
> working.
> 
> 
> 
>>
>> simply,
>>
>> def exc_decor(fn):
>> @functools.wraps(fn)
>> def wrapper(*args, **keywords):
>> try:
>> return fn(*args, **keywords):
>> except:
>> #...
>> raise
>> return wrapper
>>
>> class X(...):
>>@exc_decor
>>def foo(self, arg):
>>   pass
>>
>> (if targeting pre-decorator Python, the code would look different of
>> course)
>>
>> This way, the function itself is decorated, and the function returned by
>> the decorator is bound to the object. It'll just work as expected, no
>> trickery required.
> 
> Thanks for this. I remember having some problems decorating instance
> methods in the past which is why I started doing it as in the original
> post. Your method seems just fine though.
> 
> Thanks,
> John.
> 

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


Re: Another MySQL Problem

2010-06-23 Thread Victor Subervi
On Wed, Jun 23, 2010 at 12:51 PM, Stephen Hansen  wrote:

> The problem is not this line but:
>
>
>   File "/var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py", line
> 38, in mailSpreadsheet
> cursor.execute('select * from %s', (client,))
>
>
> This one.
>

Yes, can't use the comma, must use the percent. Will be the death of me.
Thanks,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Stephen Hansen
On Jun 23, 2010, at 11:20 AM, Victor Subervi 
wrote:

On Wed, Jun 23, 2010 at 12:51 PM, Stephen Hansen  wrote:

> The problem is not this line but:
>
>
>   File "/var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py", line
> 38, in mailSpreadsheet
> cursor.execute('select * from %s', (client,))
>
>
> This one.
>

Yes, can't use the comma, must use the percent. Will be the death of me.


No, it is really --- never use the percent, always use the comma, redesign
your table layout so percent is unneeded. Fold all the properties tables
into one.

The above with a percent is a security risk. The code is vulnerable to
attack. Considering said vulnerability is now published online-- what can be
attacked will be attacked :)

--Stephen via iPad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread Terry Reedy

On 6/23/2010 1:39 AM, Dennis Lee Bieber wrote:

On Tue, 22 Jun 2010 15:55:51 -0700, Stephen Hansen
  declaimed the following in
gmane.comp.python.general:


I second Forth. Learning and using that was -- slightly painful, but


Just pick up any advanced HP programmable calculator... RPL is a
close substitute


Or study the current CPython rpn stack machine.

>>> from dis import dis

>>> def f(a,b,c): return (a+b)*c

>>> dis(f)
  1   0 LOAD_FAST0 (a)
  3 LOAD_FAST1 (b)
  6 BINARY_ADD
  7 LOAD_FAST2 (c)
 10 BINARY_MULTIPLY
 11 RETURN_VALUE


--
Terry Jan Reedy

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


Re: Jew JUDGE shows off JEW POWER by BULLYING and BLACKMAILING a BLACK PRESIDENT OBAMA

2010-06-23 Thread nanothermite911fbibustards
FASCINATING !!!
An ECOLOGICAL DISASTER is taking place.
There is a need for HERCULEAN effort to STOP the oil spill.
Then there is need for a THOROUGH study of the incident and EXEMPLARY
PUNISHMENT of ALL THE OIL COMPANY BASTARDS, Brits, Halliburtons and
ALL of them.
But the JUDGE is worried about his interests ???

Recent disclosure documents indicate that Feldman, who was appointed
to the bench by President Ronald Reagan, has had financial holdings in
energy companies.

Recent disclosure documents indicate that Feldman, who was appointed
to the bench by President Ronald Reagan, has had financial holdings in
energy companies.

Recent disclosure documents indicate that Feldman, who was appointed
to the bench by President Ronald Reagan, has had financial holdings in
energy companies.


On Jun 22, 8:30 pm, small Pox  wrote:
> Jew Judges NEVER came out against the CRIMES of BUSH and CHENEY and
> LARRY    S I L V E R    S T E I N   -   The main player in 911
>
> Jews are coming out from the directions of Corporations, Mafias,
> Legislators, and now Judge to SUBVERT the UNITED STATES.
>
> Please listen to the Speech of Mr Benjamin H Freedman 
> onhttp://iamthewitness.com
> to see how they BLACKMAILED  President WOODROW WILSON to INSTALL a Jew
> Judge BRANDEIS in the SUPREME COURT - the FIRST one
>
> http://abcnews.go.com/Politics/gulf-oil-spill-disaster-judge-overrule...
> Judge Drills Hole in Deepwater Ban; Obama Promises Immediate Appeal
> Judge: Drilling Moratorium 'Cannot Justify' Effects on Local Economy
>
> 123 comments
> By ARIANE de VOGUE and JAKE TAPPER
> WASHINGTON, June 22, 2010
>
>  A federal judge ruled today that the Interior Department had acted
> "arbitrarily" when it issued a six-month moratorium on all pending,
> current or approved drilling plans for new deepwater wells in the Gulf
> of Mexico   and Pacific Ocean  and agreed to lift the ban.
> Scientists believe oil is depleting water of oxygen, driving predators
> to shore.
>
> Judge Martin L.C. Feldman granted a preliminary injunction to Hornbeck
> Offshore Services to lift the moratorium, saying that the government
> "failed to cogently reflect the decision to issue a blanket, generic,
> indeed punitive, moratorium."
>
> The Administrative Procedure Act authorizes judges to review the
> actions of executive branch agencies only if the action is found to be
> "arbitrary, capricious, and abuse of discretion, or not otherwise in
> accordance with the law."
>
> Feldman said a report by Secretary of the Interior Ken Salazar calling
> for the moratorium went too far and that he was "unable to divine or
> fathom a relationship between the findings and the immense scope of
> the moratorium."
>
> Recent disclosure documents indicate that Feldman, who was appointed
> to the bench by President Ronald Reagan, has had financial holdings in
> energy companies.
>
> The Department of Justice said it would immediately appeal the
> decision.
>
> On Jun 22, 2:38 pm, nanothermite911fbibustards
>
> - Hide quoted text -
> - Show quoted text -
>
>  wrote:
> > The FASCINATING Secret Relationship Between PROFLIGATE WHITES and
> > MISLEADER JEWS
> > A fascinating relationship has existed between the PROFLIGATE WHITES
> > of the European continent and the MISLEADING and MANIPULATING JEWS
> > for more than a thousand years.
> > The understanding of the world history can never commence without a
> > focus on this historical point of view.
> > We will slowly slowly reveal parts of this comprehensive treatise.

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


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread Rhodri James
On Wed, 23 Jun 2010 04:25:38 +0100, rantingrick   
wrote:



On Jun 22, 9:31 pm, MRAB  wrote:


[snip]
Napoleon once said "Never interrupt your enemy when he is making a
mistake."! :-)


And how exactly does your example express itself in a more
"syntactically-correct" "linear-flow" than the two code snippets i
provided earlier, hmmm?


You did rather carefully pick an example where Python's syntax flow the  
other way round and then present all the least Pythonic paraphrases of the  
Ruby functional approach.


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


How to send a non-standard IMAP command?

2010-06-23 Thread Xianwen Chen
Dear Pythoners,

I need to send one line of commands to an IMAP server. The commands
are not standard IMAP protocols, hence it's not specified in
http://docs.python.org/library/imaplib.html. Can you please give me a
hint?

Best regards,

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


Pythonic Idiom For Searching An Include Path

2010-06-23 Thread Tim Daneliuk
Given a program 'foo' that takes a command line argument '-I
includefile', I want to be able to look for 'includefile' in a path
specified in an environment variable, 'FOOPATH'.

I'd like a semantic that says:

  "If 'includefile' contains one or more path separator characters,
   ignore 'FOOPATH'. If it contains no path separators, look for it in
   the paths specified by 'FOOPATH', beginning with the leftmost path
   first."

Is there a standard Pythonic idiom for doing this or do I need to cook
up my own.


TIA,
-- 

Tim Daneliuk tun...@tundraware.com
PGP Key: http://www.tundraware.com/PGP/

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


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread rantingrick
On Jun 23, 4:43 pm, "Rhodri James" 
wrote:

> > And how exactly does your example express itself in a more
> > "syntactically-correct" "linear-flow" than the two code snippets i
> > provided earlier, hmmm?
>
> You did rather carefully pick an example where Python's syntax flow the  
> other way round

"rather carefully picked" you say? As if built-in functions are hardly
ever used? No I think *your* statement was "rather carefully picked"
to try and discredit me. Sorry my friend that might work on the less
astute readers round here, but it has no effect on me ;-)

> and then present all the least Pythonic paraphrases of the  
> Ruby functional approach.

What? Did you just use the words "Pythonic" and "Ruby" in the same
sentence all the while keeping a strait face? Ruby's naturally linear
phrasing is one thing i like about the language (and map of course),
short of those two niceties i prefer Python.

Would you like to present another way of achieving the same code that
makes Python look better, i would love to see it. Here is an even more
interesting example of "Ruby linear-flow" verses "Python lisp-style-
nesting"...

RUBY:
["three","one","two"].map{|x| x.capitalize}.sort.join(',')

PYTHON
','.join(sorted(map(lambda x:x.title(), ["three", "one", "two"])))

I do the Python code all the time without thinking twice about it. But
to a noob i'll bet Ruby is more decipherable in these cases. It's
ironic that Python was created by a westerner and we read it from
right to left, and Ruby was created by a easterner and we read it left
to right. Go figure?

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


Re: Should I Learn Python or Ruby next?

2010-06-23 Thread Stephen Hansen
> Would you like to present another way of achieving the same code that
> makes Python look better, i would love to see it. Here is an even more
> interesting example of "Ruby linear-flow" verses "Python lisp-style-
> nesting"...
>
> RUBY:
> ["three","one","two"].map{|x| x.capitalize}.sort.join(',')
>
> PYTHON
> ','.join(sorted(map(lambda x:x.title(), ["three", "one", "two"])))

','.join(x.title() for x in sorted(["three", "one", "two"]))

> I do the Python code all the time without thinking twice about it. But
> to a noob i'll bet Ruby is more decipherable in these cases. It's
> ironic that Python was created by a westerner and we read it from
> right to left, and Ruby was created by a easterner and we read it left
> to right. Go figure?

You read Python from right-to-left; "we" don't-- I don't.

--Stephen via iPad.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send a non-standard IMAP command?

2010-06-23 Thread Tim Chase

On 06/23/2010 05:22 PM, Xianwen Chen wrote:

I need to send one line of commands to an IMAP server. The commands
are not standard IMAP protocols, hence it's not specified in
http://docs.python.org/library/imaplib.html.


Sounds like you want to use the imaplib's IMAP4.xatom() to send a 
custom command to your IMAP server:


http://docs.python.org/library/imaplib.html#imaplib.IMAP4.xatom

Given that you don't detail what you want to send or expect back, 
it's a little hard to give you more than that, but at least that 
should get you started.  However, the full source to imaplib is 
in your $PYTHONLIB directory so you can see how other commands 
are implemented and responses are interpreted.


-tkc







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


modifying standard library functionality (difflib)

2010-06-23 Thread Vlastimil Brom
Hi all,
I'd like to ask about the most reasonable/recommended/... way to
modify the functionality of the standard library module (if it is
recommended at all).
I'm using difflib.SequenceMatcher for character-wise comparisons of
the texts; although this might not be a usual use case, the results
are fine for the given task; however,  there were some cornercases,
where the shown differences were clearly larger than needed. As it
turned out, this is due to a kind of specialcasing of relatively more
frequent items; cf.
http://bugs.python.org/issue1528074#msg29269
http://bugs.python.org/issue2986
The solution (or workaround) for me was to modify the SequenceMatcher
class by adding another parameter checkpopular=True which influences
the behaviour of the __chain_b function accordingly. The possible
speed issues with this optimisation turned off (checkpopular=False)
don't really matter now and the comparison results are much better for
my use cases.

However, I'd like to ask, how to best maintain this modified
functionality in the sourcecode.
I tried some possibilities, which seem to work, but I'd appreciate
suggestions on the preferred way in such cases.
- It is simply possibly to have a modified sourcefile difflib.py in
the script directory.
- Furthermore one can subclass difflib.SequenceMatcher an overide its
__chain_b function (however the name doesn't look like a "public"
function ...
- I guess, it wouldn't be recommended to directly replace
difflib.SequenceMatcher._SequenceMatcher__chain_b ...
In all cases I have either a copy of the whole file or the respective
function as a part of my source.

I'd appreciate comments or suggestions on this or maybe another better
approaches to this problem.

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


Re: Pythonic Idiom For Searching An Include Path

2010-06-23 Thread Chris Rebert
On Wed, Jun 23, 2010 at 3:27 PM, Tim Daneliuk  wrote:
> Given a program 'foo' that takes a command line argument '-I
> includefile', I want to be able to look for 'includefile' in a path
> specified in an environment variable, 'FOOPATH'.
>
> I'd like a semantic that says:
>
>  "If 'includefile' contains one or more path separator characters,
>   ignore 'FOOPATH'. If it contains no path separators, look for it in
>   the paths specified by 'FOOPATH', beginning with the leftmost path
>   first."
>
> Is there a standard Pythonic idiom for doing this or do I need to cook
> up my own.

Cook your own. Also, I certainly wouldn't call something this complex
a mere idiom.
You will find optparse, os.sep, and os.walk helpful in writing your code.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] filepath 0.1

2010-06-23 Thread exarkun

Hello all,

I'm happy to announce the initial release of filepath.

filepath is an abstract interface to the filesystem.  It provides APIs 
for path name manipulation and for inspecting and modifying the 
filesystem (for example, renaming files, reading from them, etc). 
filepath's APIs are intended to be easier than those of the standard 
library os.path module to use correctly and safely.


filepath is a re-packaging of the twisted.python.filepath module 
independent from Twisted (except for the test suite which still depends 
on Twisted Trial).


The low number of this release reflects the newness of this packaging. 
The implementation is almost entirely mature and well tested in real- 
world situations from its time as part of Twisted.


You can find the package on PyPI or Launchpad:

   http://pypi.python.org/pypi/filepath/0.1
   https://launchpad.net/filepath

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


Re: Jew JUDGE shows off JEW POWER by BULLYING and BLACKMAILING a BLACK PRESIDENT OBAMA

2010-06-23 Thread MooseFET
On Jun 23, 2:02 pm, nanothermite911fbibustards
 wrote:
> FASCINATING !!!
> An ECOLOGICAL DISASTER is taking place.
> There is a need for HERCULEAN effort to STOP the oil spill.
> Then there is need for a THOROUGH study of the incident and EXEMPLARY
> PUNISHMENT of ALL THE OIL COMPANY BASTARDS, Brits, Halliburtons and
> ALL of them.
> But the JUDGE is worried about his interests ???
>
> Recent disclosure documents indicate that Feldman, who was appointed
> to the bench by President Ronald Reagan, has had financial holdings in
> energy companies.
>
> Recent disclosure documents indicate that Feldman, who was appointed
> to the bench by President Ronald Reagan, has had financial holdings in
> energy companies.
>
> Recent disclosure documents indicate that Feldman, who was appointed
> to the bench by President Ronald Reagan, has had financial holdings in
> energy companies.
>

You would be hard pressed to find a judge in the area who doesn't
hold energy company stocks.  The judge has not yet done the latest
disclosure.  I really hope that it turns out he is merely wrong and
not corrupt but I would not bet on it.

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


Re: print line number and source filename

2010-06-23 Thread Peng Yu
On Tue, Jun 22, 2010 at 12:13 PM, Stephen Hansen
 wrote:
> On 6/22/10 9:44 AM, Peng Yu wrote:
>> Also, always importing the inspect module and getting the frame and
>> accessing the lineno from the frame is not very convenient to type. Is
>> there a shorter way to access the line number (for example, in C++ and
>> perl, __LINE__ can be used to access line number, which is much more
>> convenient than the way that I found in python).
>
> This all seems to be reinventing the wheel. Have you seen the logging
> module?
>
> Given this toy file:
>
>  begin -
> import logging
> logging.basicConfig(level=logging.DEBUG,format="%(asctime)s
> %(levelname)-5.5s [%(name)s %(module)s:%(funcName)s:%(lineno)d]
> %(message)s")
>
> def run():
>    x = 5
>    logging.debug("X = %d" % x)
>
> run()
> - end -
>
> 2010-06-22 10:12:07,907 DEBUG [root test:run:6] X = 5
>
> It outputs exact time, type of log message, the name of the logger
> (That's the 'root' -- you can skip if you only use one), the exact
> module (test.py), function (run) and line (6).

I tried to put the above code in a module. Say in a.b.__init__.py

%(module)s only print to "__init__". However, I need the fullname
a.b.__init__. I looked at the manual, but I don't see what format
string I should supply. Would you please let me know?

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


Re: Jew JUDGE shows off JEW POWER by BULLYING and BLACKMAILING a BLACK PRESIDENT OBAMA

2010-06-23 Thread k...@att.bizzzzzzzzzzzz
On Wed, 23 Jun 2010 19:10:45 -0700 (PDT), MooseFET  wrote:

>On Jun 23, 2:02 pm, nanothermite911fbibustards
> wrote:
>> FASCINATING !!!
>> An ECOLOGICAL DISASTER is taking place.
>> There is a need for HERCULEAN effort to STOP the oil spill.
>> Then there is need for a THOROUGH study of the incident and EXEMPLARY
>> PUNISHMENT of ALL THE OIL COMPANY BASTARDS, Brits, Halliburtons and
>> ALL of them.
>> But the JUDGE is worried about his interests ???
>>
>> Recent disclosure documents indicate that Feldman, who was appointed
>> to the bench by President Ronald Reagan, has had financial holdings in
>> energy companies.
>>
>> Recent disclosure documents indicate that Feldman, who was appointed
>> to the bench by President Ronald Reagan, has had financial holdings in
>> energy companies.
>>
>> Recent disclosure documents indicate that Feldman, who was appointed
>> to the bench by President Ronald Reagan, has had financial holdings in
>> energy companies.
>>
>
>You would be hard pressed to find a judge in the area who doesn't
>hold energy company stocks.  The judge has not yet done the latest
>disclosure.  I really hope that it turns out he is merely wrong and
>not corrupt but I would not bet on it.

You're absolutely clueless.
-- 
http://mail.python.org/mailman/listinfo/python-list


Does "distutils" support "python setup.py test"?

2010-06-23 Thread John Nagle

   Many library modules support "python setup.py test", but the
Python distutils documentation at

http://docs.python.org/distutils/configfile.html

makes no mention of it, except as a possible future extension.

   Some setup.py files have

test_suite = "modulename"

but that doesn't seem to do anything with the stock core.distutils.

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


Types missing from "types"module

2010-06-23 Thread John Nagle

  Here's dir(types), in Python 2.6.5:

['BooleanType', 'BufferType', 'BuiltinFunctionType', 
'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 
'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 
'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 
'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 
'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 
'ModuleType', 'NoneType','NotImplementedType', 'ObjectType', 
'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 
'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', 
'__builtins__', '__doc__', '__file__', '__name__', '__package__']


Seems to be missing SetType, FrozenSetType, BytesType, and
ByteArrayType.  Anything else missing?

(Arguably, "bytes" isn't really distinguished until 3.x, but
still...)

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


best way to increment an IntVar?

2010-06-23 Thread Alan G Isaac

Of course one can do
myintvar.set(myintvar.get()+1)
but surely there is a better way?

I'm surprsied that
myintvar += 1
is not allowed.

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


Re: Types missing from "types"module

2010-06-23 Thread Stephen Hansen
Sent from my iPad

On Jun 23, 2010, at 9:24 PM, John Nagle  wrote:

>  Here's dir(types), in Python 2.6.5:
>
> ['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 
> 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 
> 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 
> 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 
> 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 
> 'MethodType', 'ModuleType', 'NoneType','NotImplementedType', 'ObjectType', 
> 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 
> 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', 
> '__doc__', '__file__', '__name__', '__package__']
>
> Seems to be missing SetType, FrozenSetType, BytesType, and
> ByteArrayType.  Anything else missing?
>
> (Arguably, "bytes" isn't really distinguished until 3.x, but
> still...)
>
>   John Nagle
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Types missing from "types"module

2010-06-23 Thread Stephen Hansen
On Jun 23, 2010, at 9:24 PM, John Nagle  wrote:

>  Here's dir(types), in Python 2.6.5:
>
> ['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 
> 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 
> 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 
> 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 
> 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 
> 'MethodType', 'ModuleType', 'NoneType','NotImplementedType', 'ObjectType', 
> 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 
> 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', 
> '__doc__', '__file__', '__name__', '__package__']
>
> Seems to be missing SetType, FrozenSetType, BytesType, and
> ByteArrayType.  Anything else missing?
>
> (Arguably, "bytes" isn't really distinguished until 3.x, but
> still...)

IIUC, since Python 2.2ish you can't treat the types module as
comprehensive. It exists as a remnant from the time when there was a
difference between types and classes.

Sets and the recent additions exist solely in this new world where we
just isinstance(blah, set) or issubclass or whatnot.

--Stephen via iPad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to increment an IntVar?

2010-06-23 Thread Ben Finney
Alan G Isaac  writes:

> Of course one can do
>   myintvar.set(myintvar.get()+1)
> but surely there is a better way?

What is an IntVar? It's not a built-in type, so you'll need to tell us.

type(myintvar)

Where is it imported from?

import sys
sys.modules[type(myintvar).__module__]

> I'm surprsied that
>   myintvar += 1
> is not allowed.

Does the documentation lead you to believe it would be allowed?

help(type(myintvar))

-- 
 \   “I cannot be angry at God, in whom I do not believe.” —Simone |
  `\   De Beauvoir |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to increment an IntVar?

2010-06-23 Thread rantingrick
On Jun 24, 12:07 am, Ben Finney  wrote:
> Alan G Isaac  writes:
>
> > Of course one can do
> >    myintvar.set(myintvar.get()+1)
> > but surely there is a better way?
>
> What is an IntVar? It's not a built-in type, so you'll need to tell us.

For those who don't know; IntVar is from the module Tkinter. It is a
class to contain an integer control var used to update Tkinter widgets
that support it.

@OP: No there is not an __iadd__ method in the IntVar class but if you
really, really want to update this way just subclass IntVar and create
the method yourself. OOP is cool like dat!

You can also configure a Tkiter widget via the Python syntax w[key] =
value OR w.config(key1=value1, key2=value2, ...)


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


Re: Another MySQL Problem

2010-06-23 Thread John Nagle

On 6/23/2010 10:59 PM, Dennis Lee Bieber wrote:

On Wed, 23 Jun 2010 11:58:24 -0430, Victor Subervi
  declaimed the following in
gmane.comp.python.general:



When I have this code:




And yes -- it IS an error... You are AGAIN trying to use parameters
for SCHEMA entities, not data.


Yes.  Please post your CREATE statements, so we can see your
database schema.  If you really have one table per client, you're
doing it wrong.

John Nagle

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


Re: Types missing from "types"module

2010-06-23 Thread John Nagle

On 6/23/2010 10:08 PM, Stephen Hansen wrote:

On Jun 23, 2010, at 9:24 PM, John Nagle  wrote:


  Here's dir(types), in Python 2.6.5:

['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 
'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 
'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 
'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 
'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 
'MethodType', 'ModuleType', 'NoneType','NotImplementedType', 'ObjectType', 
'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 
'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', 
'__doc__', '__file__', '__name__', '__package__']

Seems to be missing SetType, FrozenSetType, BytesType, and
ByteArrayType.  Anything else missing?

(Arguably, "bytes" isn't really distinguished until 3.x, but
still...)


IIUC, since Python 2.2ish you can't treat the types module as
comprehensive. It exists as a remnant from the time when there was a
difference between types and classes.

Sets and the recent additions exist solely in this new world where we
just isinstance(blah, set) or issubclass or whatnot.


   Ah.  That makes sense.

   Does the "types" module go away in 3.x, then?

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


Re: Types missing from "types"module

2010-06-23 Thread Ian Kelly
On Thu, Jun 24, 2010 at 12:29 AM, John Nagle  wrote:
>   Does the "types" module go away in 3.x, then?

Not entirely, but it is greatly reduced.
-- 
http://mail.python.org/mailman/listinfo/python-list